Hi there once again!
I apologize for not posting in such a long time. There was some issue with my account and I had to find a way around it.
So, for this tutorial, I've got something interesting for y'all. I am going to show you how to use the tkinter Python library. tkinter is a builtin library to the Python programming language that allows you to create GUI. The library is very flexible and a great thing to investigate to expand your Python horizons.
Disclaimer: If you're really new to Python, I would save this for later. This does require some background knowledge.
In Every Program:In every program we make, we need this typed in:
Don't worry: I'll explain this
Your First tkinter ProgramAlright! Go ahead and run this:
When you run this program, you should get this:
Yes! A small window should appear, saying 'Hello, tkinter!'
Alright. Lets walk through this.
from tkinter import * : imports everything from the tkinter library into your program
root = Tk() : In tkinter, all objects must be assigned to a variable. A common convention is to call it 'root'. What this command does is just creates a window. Simple as that.
root.mainloop() : This loops the window until the user closes it. Of course, this command also needs a variable. In this case, it's 'root'.
label_one = Label(root, text='Hello, tkinter!') : This line creates a Label called 'label_one". The first argument, root, specifies the frame to put the label in. In this case, the frame is called 'root', the name of our window. Next, the Label function can take many parameters after that, like text, foreground color, background color, etc. The final syntaxfor labels: variable = Label(frame, text, fg, bg )
Note: To add color to text, add fg='color' after the text function. Set background color using bg='color'.
label_one.pack() : What the.pack() function does is telling tkinter to pack 'label_one' into the window. No parameters, just pack it in there. This is a necessity, as if you do not type this, your program will not work. I will show you what parameters we can add later.
FramesThe syntax to make frames:
variable = Frame(root)
variable.pack(side=, fill=, fg=, bg=, sticky=)
Note: You don't always have to put in all those parameters. Tkinter is highly flexible, with lots and lots of options.
Imagine that you're on your desktop and you highlight half of your wallpaper. Imagine that as a frame, where you can specify where objects land and don't land. You'll see why this is important very soon.
Now for this example, we're going to have two Labels and two Frames. Delete the code to create the Label, leaving only our Tkinter musts. Type this in:
frame_one = Frame(root) : This line of code creates a variable called frame_one inside our window called 'root'.
frame_one.pack() : Just pack it in there.
Now, we are going to make another frame called frame_two. Type this in:
frame_two = Frame(root): creates a frame in our window
frame_two.pack(side=BOTTOM) : This packs our frame into the bottom half of our window.
Now, you may be thinking, "Why didn't we have to say 'side=TOP' when we packed frame_one?" The answer to the question is that tkinter defaults everything to the top of the window. That would make typing that redundant, so we can just specify that we want another frame underneath the first.
Now, add two Labels, one in frame_one, and then in frame_two.
I got this:
Now you may be thinking: Wait, where are my frames? It looks like they aren't there!
Try expanding the window:
It worked!
ButtonsNow that you have the basics on how to use some Tkinter widgets, learning other functions should be easy. This is the syntax for buttons:
variable = Button(frame, text=, fg, bg, command=)
When making a button perform a function, write a function earlier in your Python code and set the parameter command=functionName. (Don't include the '( )' )
For this example, I replace the labels with buttons that print words to the console of my IDE.
In this program, when you click 'Up here' the word 'Hello' appears. When you click 'Down here' the word 'hi' appears. The code for this:
The fill command is a small but useful one. Lets say I have one label on my screen. It looks like this:
In my code, I said this:
label_one = Label(root, text='Uno', fg='white', bg='red')
label_one.pack()
Simple. But what if I added another label with a Fill command on it?
label_two = Label(root, text='Dos', fg='Black', bg='Yellow')
label_two.pack(fill=X)
It looks like this:
Normal, right? But what happens if I expand the window to the right?
The labels fills the window in the X direction!
Let's add one more in the Y direction this time.
label_three = Label(root, text='Tres', fg='blue', bg='white')
label_three.pack(side=LEFT,fill=Y)
I bet you can already guess what will happen.
Make sure you add the 'side=LEFT' in there or else it won't fill in the Y direction.
Grid/PadGrid is a useful tkinter function that allows you to place objects exactly where you want them. The grid is spoken of by using row= and column=, making it pretty easy to use.
Try typing this:
You should get something like this:
Now, what's cool about grid is that we don't need to use the.pack() function. The grid allows us to specify where exactly we want objects, and not just pack them in.
Note: When assigning rows and columns, computers always start counting at zero.
Now, try this:
You should get:
This time, we changed the row to make the labels stack on top of one another.
You can also have one object span multiple columns using the columnspan= function, as well as using the rowspan=.
Tip: If you don't like how the labels bump against each other so closely, add the function padx= or pady= after specifying the rows and columns of the grid. This is what our labels would look like after adding padx=2 when in a row side by side:
And after adding pady=2 when stacked on top of each other:
Binding is another way to add functions to your tkinter program. Lets make a program where depending on the different mouse clicks, something happens each time. When you create a function, pass it in as an event, like this:
def rightClick(event):
print("Right")
This way, Python is waiting for something to happen, called an event, like a mouse-click, a scroll, something on the keyboard typed.
Type this into your IDE: (see https://www.youtube.com/watch?v=XkCbinbgbdw&t=312s)
frame = Frame(root, width = 300, height=250) : Creates a frame in the given size.
frame.bind('<Button-1>', leftclick) : This binds the event '<Button-1>' to the function left click inside the frame only. '<Button-1>' is what Python calls the Left Click on a mouse. See more on binding and all things tkinter at the link at the bottom of this tutorial.
Syntax : frame.bind(event, function)
CanvasCanvas is a way in tkinter to draw shapes. When drawing, you need to create a canvas first. Do it like this:
variable = Canvas(root, width=, height=, bg= )
variable.pack()
There are many shapes and things to draw in canvas, but I won't list them all, I'll just show you how to create lines and rectangles.
Lines : variable.create_line(startx, starty, endx, endy, fill='color')
Rectangles: variable.create_rectangle(startx, starty, width, height, fill='color')
Note: When in canvas, 'fill' is the color command, not 'fg', and 'bg'.
Look at what I made:
Syntax for images:
variable = PhotoImage(file='image.png')
Now, when inserting images, we need to insert the image inside a Label, or tkinter will give you an error. Also, it needs to be a.png image. Try this:
There is still so much to learn about tkinter. Menus, Message boxes, and so much more. I wish I could include more, but this tutorial is getting a little long.
Please be sure to check out the link at the bottom for an amazing video series on Tkinter by thenewboston.
Thank you guys so much and have a good day!
Comments