I've been trying for a while now to find out if there is a way to pass variables to the geometry
method in Tkinter.
I know the geometry
method accepts a string:
root = Tk()
root.geometry("1200X1024")
I want to open the window based in the screen width.
root = Tk()
w = root.winfo_screenwidth()
h = root.winfo_screenheight()
What I've tried is this:
geometry = "%dX%d" % (w,h)
root.geometry(geometry)
or
root.geometry(("%dX%d" % (w,h)))
No matter how I concatenate the variables it gives this error:
TlcError: bad geometry specifier "1280X1024"
So is it possible to pass variables to the geometry
method?
The Tk.geometry
method is not very "smart" when it comes to interpreting the string you give it. Instead, it requires you to specify the window size exactly as:
<width>x<height>
Meaning, your uppercase X
is confusing it. Simply change X
to x
and your code will work fine.
#works for python 3.4
screen_width = window.winfo_screenwidth()
screen_height = window.winfo_screenheight()
screen_resolution = str(screen_width)+'x'+str(screen_height)
window.geometry(screen_resolution)
You can simplify the code using brackets with string format() function:
window.geometry("{}x{}".format(window_width, window_height))
As well as set its x and y location properties concatenating with "+":
window.geometry("{}x{}+{}+{}".format(window_width, window_height, x-coord, y-coord))
You dont need to do anything that complex just do:
root = Tk()
root.geometry("500x200") #taking x=500 and y=200 for example
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.