Is it necessary to call Tk() when writing a GUI app with Tkinter?

Terry Reedy tjreedy at udel.edu
Thu Mar 1 00:24:06 EST 2012


On 2/29/2012 10:22 PM, Rick Johnson wrote:
I do not know what book the OP is referring to,
but the current doc example is
http://docs.python.org/py3k/library/tkinter.html#a-simple-hello-world-program
My current replacement (see below) can be downloaded from the tracker:
http://bugs.python.org/issue14163

> If you want to keep things simple, i would:
>
>   1. Create the root window explicitly!

It already does that.

>   2. Bind the command of the button to root.destroy
> (command=root.destroy)

That works great. My current replacement example is uploaded to the 
issue http://bugs.python.org/issue14163

> PS: I would highly suggest against using the "from Tkinter import *".
> Instead, use "import Tkinter as tk" and prefix all module contents
> with "tk.".

I have changed the example to do that. I also showed the alternate to 
initialize a widget. Here is the current version, tested on Windows 3.2.2.

import tkinter as tk

class Application(tk.Frame):
     def __init__(self, master=None):
         tk.Frame.__init__(self, master)
         self.pack()
         self.createWidgets()

     def createWidgets(self):
         self.hi_there = tk.Button(self)
         self.hi_there["text"] = "Hello_World\n(click_me)",
         self.hi_there["command"] = self.say_hi
         self.hi_there.pack({"side": "top"})

         self.QUIT = tk.Button(self, text = "QUIT", fg = "red", command 
= root.destroy)
         self.QUIT.pack({"side": "bottom"})

     def say_hi(self):
         print("hi there, everyone!")

root = tk.Tk()
app = Application(master=root)
app.mainloop()

There is a minor problem left. The hi_there Button text has underscores 
because if I use spaces instead, tk surrounds the text with {bra ces}. 
This seems bizarre. Is there any way to have Button text with spaces and 
no braces?

-- 
Terry Jan Reedy




More information about the Python-list mailing list