📜  如何设置 gui 位置 tkinter python (1)

📅  最后修改于: 2023-12-03 15:09:15.843000             🧑  作者: Mango

如何设置 GUI 位置 - Tkinter Python

在 Tkinter 中,可以使用 geometry() 方法来设置 GUI 窗口的位置和大小。geometry() 方法需要一个字符串作为参数,该字符串的格式如下:

geometry("宽度x高度+水平位置+垂直位置")

其中:

  • 宽度和高度表示窗口的大小,以像素为单位。
  • 水平位置和垂直位置表示窗口左上角相对于屏幕左上角的坐标,以像素为单位。

例如,如果要将窗口设置为宽度为 400 像素、高度为 300 像素,同时将其位置设置为屏幕的中心:

root.geometry("400x300+{}+{}".format(int(root.winfo_screenwidth()/2 - 200), int(root.winfo_screenheight()/2 - 150)))

在这个示例中,root 是 Tkinter 应用程序的主窗口对象。首先,我们通过 winfo_screenwidth()winfo_screenheight() 方法获取屏幕的宽度和高度,然后将其除以 2 并减去窗口的一半,从而得到窗口左上角的坐标。

除了使用 geometry() 方法外,还可以使用 place() 方法手动放置窗口:

root.place(width=400, height=300, x=int(root.winfo_screenwidth()/2 - 200), y=int(root.winfo_screenheight()/2 - 150))

使用 place() 方法时,需要指定窗口的宽度和高度,以及左上角的坐标。与使用 geometry() 方法相比,place() 方法可以更精确地控制窗口的位置和大小。

注意,如果你使用了 mainloop() 方法来运行 Tkinter 应用程序,那么在调用 geometry()place() 方法之前必须先调用 mainloop() 方法。

代码示例:

import tkinter as tk

root = tk.Tk()
root.title("设置 GUI 位置")

# 使用 geometry() 方法设置窗口位置和大小
root.geometry("400x300+{}+{}".format(int(root.winfo_screenwidth()/2 - 200), int(root.winfo_screenheight()/2 - 150)))

# 使用 place() 方法设置窗口位置和大小
# root.place(width=400, height=300, x=int(root.winfo_screenwidth()/2 - 200), y=int(root.winfo_screenheight()/2 - 150))

root.mainloop()

参考资料: