Tkinter Confusion

7stud bbxx789_05ss at yahoo.com
Sun Feb 17 20:21:16 EST 2008


On Feb 17, 12:36 pm, MartinRineh... at gmail.com wrote:
> Everything I've read about Tkinter says you create your window and
> then call its mainloop() method. But that's not really true. This is
> enough to launch a default window from the console:
>
> >>>from Tkinter import *
> >>>foo = Tk()
>

You shouldn't care what happens in an interactive python session.  In
fact, you can take years off your life trying to figure out why the
output of an interactive session is different from the output of a
python program.  Here is how to create a basic window with one widget:

import Tkinter as tk

root = tk.Tk()

label = tk.Label(root, text='hello world')
label.pack()  #makes widget visible

root.mainloop()


Adding in some more details:


import Tkinter as tk

root = tk.Tk()
root.geometry('600x400')
root.config(background='red')

label = tk.Label(root, text='hello world', background='gray')
label.pack()  #makes widget visible

root.mainloop()



> Google's great, but it has no truth meter. Do I inherit from Frame?

A frame is used to group widgets.  You can have multiple frames each
containing a group of widgets.  That will allow you to place the group
as a whole at a specific location in the window.  Here's how to use
frames to organize widgets:

import Tkinter as tk

root = tk.Tk()
root.geometry('600x400')
root.config(background='red')

frame1 = tk.Frame(root)
label1 = tk.Label(frame1, text='hello world', background='gray')
label2 = tk.Label(frame1, text='goodbye', background='gray')

label1.pack()  #makes label visible
label2.pack()  #makes label visible
frame1.pack(side=tk.BOTTOM)  #makes frame visible

frame2 = tk.Frame(root)
label3 = tk.Label(frame2, text='yes', background='yellow')
label4 = tk.Label(frame2, text='no', background='yellow')
label5 = tk.Label(frame2, text='maybe', background='yellow')

label3.pack()
label4.pack()
label5.pack()
frame2.pack(side=tk.TOP)

frame3 = tk.Frame(root)
label6 = tk.Label(frame3, text='a', background='blue')
label7 = tk.Label(frame3, text='b', background='blue')
label8 = tk.Label(frame3, text='c', background='blue')

label6.pack()
label7.pack()
label8.pack()
frame3.pack(side=tk.LEFT)

root.mainloop()


> Do I use
> Tk() or toplevel()? (Support for both and if a cogent explanation of
> the differences exists, I didn't find it.)
>

Tk() for you first window; Toplevel() for any additional windows you
want to open:


import Tkinter as tk

root = tk.Tk()
root.geometry('300x200+50+50')  #+x+y positions window
root.config(background='red')

label = tk.Label(root, text='hello world', background='gray')
label.pack()

window2 = tk.Toplevel()
window2.geometry('300x200+400+50')

root.mainloop()






More information about the Python-list mailing list