Tkinter

Getting Started

Copy this simple template to get a window to work with

import tkinter
window = tkinter.Tk()

# Here is where you will put
# code later

window.mainloop()

Adding a bit of text

To add a bit of text we need to add this code:

label1Text = tkinter.StringVar()
label1 = tkinter.Label(window, textvariable=label1Text)
label1Text.set("Hello There!")

label1.pack()

Making it a little bigger

We can make it bigger by adding padding around the label using the padx and pady arguments.

label1 = tkinter.Label(window, textvariable=label1Text, padx=50, pady=50)

Adding a button

We can now add a button by adding this code under the label code. The button will change our label when it is pressed.

 

 

 

 

 

Now you could add padding to the button.

def button1Callback():
    label1Text.set("You clicked the button!")

button1 = tkinter.Button(window, text="Click Me!", command=button1Callback)

button1.pack()

Giving it a Title

window.title("whatever you want your title to be ¯\_(ツ)_/¯")

Custom Cursors?!

You can change the cursor when you hover over a widget with the cursor argument.

  • arrow
  • circle
  • clock
  • cross
  • dotbox
  • exchange
  • fleur
  • heart
  • man
  • mouse
  • pirate
  • plus
  • shuttle
  • sizing
  • spider
  • spraycan
  • star
  • target
  • tcross
  • trek
  • watch
label1 = tkinter.Label(..., cursor="spraycan")
#                                   ↑
# where spraycan is one from the list to the right

Using the Grid

At the moment your window is layed out like this:

Widget 1

Widget 2

Widget 3

Widget 4

Widget 5

Using the Grid

We can take advantage of the grid system to put things almost where ever we want.

Widget 1

Widget 2

Widget 3

Widget 4

Widget 5

Widget 6

Using the Grid

# ...
label1 = tkinter.Label(bla bla bla).grid(row=0, column=0)
#                                  ↑
# ...

# ...
button1 = tkinter.Button(bla bla bla).grid(row=0, column=1)
#                                    ↑
# ...
.grid(row=?, column=?)

You can also add padding to the grid like the button and the label, and it looks much better on the grid

Asking for an Input

label2 = tkinter.Label(window, text="What's your name?").grid(row=1, column=0, padx=20, pady=20)

entry1 = tkinter.Entry(window).grid(row=1, column=1, padx=20, pady=20)

label2.pack()
entry1.pack()

Challenge: Add a button that when clicked, puts the contents of entry1 into label1? You're going to need entry1.get() to get the contents.

deck

By Jake Walker

deck

  • 632