views:

114

answers:

1

I'm trying to center a Tkinter window. I know I can programatically get the size of the window and the size of the screen and use that to set the geometry, but I'm wondering if there's a simpler way, this being Python and all.

I know that in Java's Swing library, you can do this with a simple call to frame.setLocationRelativeTo(null), so I guess I'm wondering if there's an equivalent simple call that I can make in Tkinter?

+4  A: 

Tkinter isn't exactly the most powerful of toolkits (it's very, VERY basic).

I'm not aware of something so simple in Tkinter, but you can do this:

w = root.winfo_screenwidth()
h = root.winfo_screenheight()
rootsize = tuple(int(_) for _ in root.geometry().split('+')[0].split('x'))
x = w/2 - rootsize[0]/2
y = h/2 - rootsize[1]/2
root.geometry("%dx%d+%d+%d" % (rootsize + (x, y)))

pyGTK OTOH is much better:

import pygtk
import gtk

win = gtk.Window(gtk.TOPLEVEL)
win.resize(300, 300)
win.set_position(gtk.WIN_POS_CENTER)
win.show()

Basically, Tkinter is good for a cheap and easy GUI - but it won't look that pretty without some serious work. The more advanced toolkits (pyGTK, PyQT) are a lot "prettier", but not as common, as Tkinter usually comes bundled with python. So if you want a pretty GUI, use a better toolkit, but if you just want something cheap and easy, use Tk.

Wayne Werner
"not most powerful" is a bit subjective. It has as much "power" as other toolkits (depending on your definition of "power"), it just doesn't do as much hand-holding. It's the difference between building a house with pre-made walls (some other toolkits) or building it from a pile of lumber (Tk). You can pretty much do anything in Tkinter that you can do in other toolkits, you just have to sometimes work a little for it.
Bryan Oakley
Seems to confirm my suspicions, thanks!
psicopoo
@Bryan - that's precisely what I mean by power. Sure you can get across the United States in a Yugo (maybe) and a Ferrari, but one of them can get you there a lot faster. Of course they both have the power to interact with the user in certain ways, but Tkinter doesn't have the power to let you write larger programs in less lines (and with less effort). Of course, smaller programs are actually easier in Tkinter because you don't have to worry about the same overhead for widgets as other toolkits, and that's what I love Tkinter for - writing smaller programs. @psicopoo, you're welcome!
Wayne Werner