Set initial size in TKinter

Eric Brunel eric.brunel at pragmadev.nospam.com
Tue Dec 20 10:20:08 EST 2011


In article <mailman.3861.1324379384.27778.python-list at python.org>,
 Gabor Urban <urbangabo at gmail.com> wrote:
> Hi,
> 
> I am quite newbie with Tkinter and I could not find the way to set the
> size of the application. (I could find the method to make it
> resizeable, though :-)) ) Any ideas, suggestions or links to
> references are wellcome.

Usually, the best way is to use the geometry method on instances of Tk 
or Toplevel. For example, if you have a variable named root which is the 
instance of Tk, you can do:

root.geometry('500x400')

This will make the window 500 pixels wide and 400 pixels high.

> Here is my code:
> 
> from Tkinter import *
> 
> class Application(Frame):
>     def say_hi(self):
> 	self.db += 1
>         print 'hi there, -->> UG everyone! db = %d'%self.db
> 
> ## TODO: meretezhetoseg
>     def createWidgets(self):
>       top = self.winfo_toplevel()
>       top.rowconfigure(0,weight = 1)
>       top.columnconfigure(0,weight = 1)
>       self.rowconfigure(0,weight = 1)
>       self.columnconfigure(0,weight = 1)
>       self.QUIT = Button(self)
>       self.QUIT["text"] = "QUIT"
>       self.QUIT["fg"]   = "red"
>       self.QUIT["command"] =  self.quit
> 
>       self.QUIT.pack({"side": "left"})
> 
>       self.hi_there = Button(self)
>       self.hi_there["text"] = "Hello",
>       self.hi_there["command"] = self.say_hi
> 
>       self.hi_there.pack({"side": "left"})
> 
>     def __init__(self, master=None):
>         Frame.__init__(self, master)
>         self.pack()
>         self.createWidgets()
> 	self.db = 0
> 
> app = Application()
> app.master.title('UG test')
> app.mainloop()

Where did you find an example code looking like this? This looks like 
veeeeeery old conventions for Tkinter programsŠ

For example, there's no need at all to do:

self.QUIT = Button(self)
self.QUIT["text"] = "QUIT"
self.QUIT["fg"]   = "red"
self.QUIT["command"] =  self.quit

This can be done in a single line:

self.QUIT = Button(self, text='QUIT', fg='red', command=self.quit)

The same goes for self.QUIT.pack({"side": "left"}). Nowadays, this is 
always written self.QUIT.pack(side="left").

And you should avoid creating only an instance of Frame. This actually 
creates a window, but it's a side-effect. Windows are created by 
instantiating Tk for the main one, and Toplevel for all others. Having 
only a Frame will cause problems later, for example if you want to add a 
menu to the window: You can do so on instances of Tk or Toplevel, but 
not on framesŠ

HTH
 - Eric -



More information about the Python-list mailing list