from __future__ import print_function try: import Tkinter except ImportError: import tkinter as Tkinter # This time, we alter the pattern very slightly by moving # the import statements inside the function body. This # is marginally better in that (a) if this module was # imported but not used, Tkinter and Canvas would not # be imported; and (b) references to Tkinter and Canvas # in the functions are a hair faster than if we imported # at the module level. def main(): app = Tkinter.Frame() app.grid(sticky="nsew") # We have to tell the toplevel window that the frame # that we created should be adjustable (weight != 0) top = app.winfo_toplevel() top.columnconfigure(0, weight=1) top.rowconfigure(0, weight=1) make_ui(app) app.mainloop() # In this program, we create a Canvas widget in the # main application frame and populate it with some # graphical items. The Canvas module defines classes # for rectangles, ovals, lines and several other # graphical forms. All of them derive from the # CanvasItem class, which provides many methods such # as "bind" and "config" (which act similarly to # methods of the same name in widgets) and "move" # (which is not defined for widgets). The first # argument to a CanvasItem subclass is a Canvas # instance ("c" in this case). The second argument # is a list of coordinates. For rectangles, the # coordinates are the coordinates of two opposite # corners; for ovals, they are the coordinates of # the opposite corners of the smallest rectangle # containing the oval; for lines, the list are the # coordinates for consecutive vertices in the lines. # All other arguments are keyword arguments. The # most commonly used is "fill" which defines the # color of the item. def make_ui(app): c = Tkinter.Canvas(app, width=400, height=400, bg="cyan") # Just as above, we need to tell "app" that the widget # in row 0, column 0 is resizable app.columnconfigure(0, weight=1) app.rowconfigure(0, weight=1) c.grid(row=0, column=0, sticky="nsew") r = c.create_rectangle((10, 10, 20, 30), fill="green") r2 = c.create_oval((300, 200, 100, 100), fill="blue") l = c.create_line((20, 30, 200, 100), fill="red") if __name__ == "__main__": main() print("Finished")