How to set the size of a window? [duplicate]

无人久伴 提交于 2019-12-13 08:22:08

问题


How can I resize root window?

try:                        # In order to be able to import tkinter for
    import tkinter as tk    # either in python 2 or in python 3
except ImportError:
    import Tkinter as tk


root = tk.Tk()
tk.mainloop()

How can I resize window?

try:                        # In order to be able to import tkinter for
    import tkinter as tk    # either in python 2 or in python 3
except ImportError:
    import Tkinter as tk


root = tk.Tk()
window = tk.Toplevel(root)
tk.mainloop()

回答1:


One could set the size of a window (be it a Tk instance or Toplevel instance) using geometry method:

# identical to root.geometry('256x512')
root.geometry('{}x{}'.format(256, 512))

or:

# identical to window.geometry('512x256')
window.geometry('{}x{}'.format(512, 256))

Additionally using geometry method one could also determine the upper-left corner of a window:

window.geometry('+{}+{}'.format(16, 32))

or perhaps both at once:

#identical to window.geometry('512x256+16+32')
window.geometry('{}x{}+{}+{}'.format(512, 256, 16, 32))

More generally one could use winfo_toplevel in order to easily set the size of the window from its children:

widget.winfo_toplevel().geometry('{}x{}+{}+{}'.format(512, 256, 16, 32))

Example

Here's an example that sets both the size and placement coordinates of a window through a children widget's reference:

try:                        # In order to be able to import tkinter for
    import tkinter as tk    # either in python 2 or in python 3
except ImportError:
    import Tkinter as tk


def on_button_press(widget):
    width = 512
    height = 256
    x = 16
    y = 32
    widget.winfo_toplevel().geometry('{}x{}+{}+{}'.format(width, height, x, y))


if __name__ == '__main__':
    root = tk.Tk()
    window = tk.Toplevel(root)
    button = tk.Button(window, text="Resize & Place")
    #the line below is related to calling a method when a button is pressed
    button['command'] = lambda w=button: on_button_press(w)
    button.pack()
    tk.mainloop()


来源:https://stackoverflow.com/questions/49098565/how-to-set-the-size-of-a-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!