Frame, Canvas, and Button classes.
As with other Python classes, to create an instance of a class, you call its constructor (see the next page).
>>> from tkinter import * >>> root = Tk()
root a title. Then run the event loop,
which renders the GUI and waits for the user to perform some action.
This is an infinite loop; it runs until the user closes the window or
does something else that causes the program to quit.
>>> root.title("Hello world!")
>>> root.mainloop()
widgetclass(master, option=value, ...)The constructor creates an instance of the widget class as a child to the given master window (an instance of some widget class), and using the given options. All options have default values, so in the simplest case you only need to specify the master.
grid() method.
grid() tells the widget where to appear within its master window unless this is
obvious.Tk class) is the master window for the frame.
grid() method doesn't
take any arguments because it doesn't need to specify a special location within its master window.
As we'll see later, grid() has various optional arguments to specify particular locations.
>>> root = Tk()
>>> root.title("Just a frame")
''
>>> frame = Frame(root)
>>> frame.grid()
>>> root.mainloop()
keys() method. To change the settings for one or more options, use either the configure() or config() method (which are equivalent). To see the current setting for an option, use the method cget().
>>> frame.keys() ['bd', 'borderwidth', 'class', 'relief', 'background', 'bg', 'colormap',
'container', 'cursor', 'height', 'highlightbackground', 'highlightcolor', 'highlightthickness', 'padx', 'pady', 'takefocus', 'visual', 'width'] >>> frame.config(width=500, height=500, bg='pink') >>> frame.cget("width") 500 >>> frame.cget("bg") 'pink'
Canvas class has a number of methods for painting figures within it. Each of these returns an int which serves as an id for the graphical object that is created.
Note that a graphical object is not an actual Python object, that is, an instance of some widget class.
>>> root = Tk() >>> frame = Frame(root) >>> frame.grid() >>> canvas = Canvas(frame, width = 400, height = 200, bg='yellow') >>> canvas.grid() >>> canvas.create_oval(10, 30, 50, 50) 1 >>> canvas.create_rectangle(50, 50, 100, 75) 2 >>> canvas.create_line(15, 15, 85, 90) 3 >>> root.mainloop()
itemconfig() method.
>>> canvas = Canvas(frame, width = 400, height = 200, bg='yellow') >>> canvas.grid() >>> oval = canvas.create_oval(10, 30, 50, 50) >>> canvas.itemconfig(oval, fill='red')
coords method, which takes the
graphical object id and the new coordinates as arguments.Canvas.
In the __init__() method, be sure to also call the __init__() method for
Canvas.
Canvas, that draws a given number of small rectangles in random positions on a
canvas of given width and height.
>>> label = Label(frame, text="Press the button.") >>> label.grid() >>> button = Button(frame, text="Press me.") >>> button.grid()
command option.
>>> def print_hello():
>>> print("hello!")
>>> button.config(command = print_hello)
command option is a function object. This is an example of a callback, because when the user presses the button the flow of execution "calls back" to that function.command option when the mouse button is released.
To affect the behavior of the button when it is clicked, we just need to assign the appropriate function
to the command option.
bind() method and creating new event handlers.
x and y
attributes) of the event.
def print_coords(event):
la = Label(frame, text = "Clicked: " + str(event.x) + " " + str(event.y))
la.grid()bind() is a widget method.
The first argument to bind() is a string describing
the type of event, and the second is the appropriate event handler. The following
code creates a binding for a click of the first mouse button in a canvas.
canvas = Canvas(frame)
canvas.bind("<Button-1>", print_coords)
<ButtonRelease-1>: the first mouse button was released<Motion>: the mouse was moved<B1-Motion>: the mouse was moved with the first button pressed<Key>: the user pressed any key<KeyPress-x>: the user pressed the 'x' key<Enter>: the mouse entered the widgetCanvas, use the Canvas method tag_bind(), which takes the object id, the event type string, and the handler.insert() method allows you to put text into an entry or text box. The get() method returns the contents of the entry (which the user may have changed).
>>> root = Tk() >>> entry = Entry(root, width=100) >>> entry.grid() >>> entry.insert(END, "A line of text.") >>> print(entry.get()) A line of text. >>> entry.insert(1, "nother") >>> print(entry.get()) Another line of text.
Text widgets, locations are specified using a dotted index, like 1.1, which has the line number before the dot and the column number after. The get() method takes a start and end index as arguments.
>>> text = Text(root, width=100, height=5) >>> text.insert(END, "A line of text.") >>> print(text.get(0.0, END)) A line of text. >>> text.insert(1.1, 'nother') >>> print(text.get(1.5, END)) er line of text.
'<Return>'.
create_line, create_rectangle,
and create_text
tags.
A tag must be a string.
Any number of objects can have the same tag, and an object may have more than one.
move.coords.tag_bind.
itemconfigure.
itemcget.grid to display the widget.
from tkinter import * root = Tk() frame = Frame(root) Button(frame, text="A useless button").grid() frame.grid() root.mainloop()
grid.
row and column specify cells within the container where
the widget should go.
rowspan and columnspan cause the widget to take up multiple cells.
row, column, and columnspan:
layout1.py
from tkinter import * root = Tk() frame = Frame(root) label1 = Label(frame, text='Name') label1.grid(row=0, column=0) entry1 = Entry(frame) entry1.grid(row=0, column=1) label2 = Label(frame, text='PIN') label2.grid(row=1, column=0) entry2 = Entry(frame) entry2.grid(row=1, column=1) button = Button(frame, text='OK') button.grid(row=2, columnspan=2) frame.grid() root.mainloop()
Canvas class:
layout2.py
from tkinter import * root = Tk() frame = Frame(root) leftcanvas = Canvas(frame) label1 = Label(leftcanvas, text='Name') label1.grid(row=0, column=0) entry1 = Entry(leftcanvas) entry1.grid(row=0, column=1) label2 = Label(leftcanvas, text='PIN') label2.grid(row=1, column=0) entry2 = Entry(leftcanvas) entry2.grid(row=1, column=1) button = Button(leftcanvas, text='OK') button.grid(row=2, columnspan=2) leftcanvas.grid(row=0, column=0) rightcanvas = Canvas(frame) ur_canvas = Canvas(rightcanvas, width=50, height=50, bg='green') ur_canvas.grid(row=0) lr_canvas = Canvas(rightcanvas, width=75, height=75, bg='yellow') lr_canvas.grid(row=1) rightcanvas.grid(row=0, column=1) frame.grid() root.mainloop()
grid() has other options to control where the widget is positioned within its cell; see this help page.>>> from tkinter import * >>> root = Tk()
>>> canvas = Canvas(root, width=500, height=500) >>> canvas.grid() >>> button = Button(root, text="Press me.") >>> button.grid()
grid() method.
A simple way to handle this is to always call widget.grid() immediately after the widget is created.keys() methodconfig() methodcget() method
>>> frame.keys() ['bd', 'borderwidth', 'class', 'relief', 'background', 'bg', 'colormap',
'container', 'cursor', 'height', 'highlightbackground', 'highlightcolor', 'highlightthickness', 'padx', 'pady', 'takefocus', 'visual', 'width'] >>> frame.config(width=500, height=500, bg='pink') >>> frame.cget("width") 500
>>> def print_coords(event):
>>> print("Clicked: ", event.x, event.y)
bind() method. This creates an association between the widget, a particular event, and the event handler.
>>> canvas.bind("<Button-1>", print_coords)
command option available for some widgets (e.g. Buttons) is simply a shortcut for creating event bindings.grid() method.
mainloop() method of your root window, which will create your GUI and start the event loop.
>>> root.mainloop()