📜  Python| Tkinter 中的几何方法

📅  最后修改于: 2022-05-13 01:55:43.550000             🧑  作者: Mango

Python| Tkinter 中的几何方法

Tkinter 是一个Python模块,用于开发 GUI(图形用户界面)应用程序。它与Python一起提供,因此您不必使用pip命令安装它。

Tkinter 提供了很多方法;其中之一是geometry()方法。该方法用于设置 Tkinter 窗口的尺寸,用于设置主窗口在用户桌面上的位置。

代码 #1:不使用几何方法的 Tkinter 窗口。

Python3
# importing only those functions which are needed
from tkinter import Tk, mainloop, TOP
from tkinter.ttk import Button
  
# creating tkinter window
root = Tk()
  
# Create Button and add some text
button = Button(root, text = 'Geeks')
# pady is used for giving some padding in y direction
button.pack(side = TOP, pady = 5)
  
# Execute Tkinter
root.mainloop()


Python3
# importing only those functions which
# are needed
from tkinter import Tk, mainloop, TOP
from tkinter.ttk import Button
  
# creating tkinter window
root = Tk()
  
# creating fixed geometry of the
# tkinter window with dimensions 150x200
root.geometry('200x150')
  
# Create Button and add some text
button = Button(root, text = 'Geeks')
button.pack(side = TOP, pady = 5)
  
# Execute Tkinter
root.mainloop()


Python3
# importing only those functions which
# are needed
from tkinter import Tk, mainloop, TOP
from tkinter.ttk import Button
  
# creating tkinter window
root = Tk()
  
# creating fixed geometry of the
# tkinter window with dimensions 150x200
root.geometry('200x150 + 400 + 300')
  
# Create Button and add some text
button = Button(root, text = 'Geeks')
button.pack(side = TOP, pady = 5)
  
# Execute Tkinter
root.mainloop()


输出:

不使用几何方法的 Tkinter 窗口

运行应用程序后,您将看到 Tkinter 窗口的位置在屏幕的西北位置,并且窗口的大小也很小,如输出所示。代码#2:

Python3

# importing only those functions which
# are needed
from tkinter import Tk, mainloop, TOP
from tkinter.ttk import Button
  
# creating tkinter window
root = Tk()
  
# creating fixed geometry of the
# tkinter window with dimensions 150x200
root.geometry('200x150')
  
# Create Button and add some text
button = Button(root, text = 'Geeks')
button.pack(side = TOP, pady = 5)
  
# Execute Tkinter
root.mainloop()

输出:

不使用几何方法示例 2 的 Tkinter 窗口

运行应用程序后,您会看到 Tkinter 窗口的大小发生了变化,但屏幕上的位置相同。代码#3:

Python3

# importing only those functions which
# are needed
from tkinter import Tk, mainloop, TOP
from tkinter.ttk import Button
  
# creating tkinter window
root = Tk()
  
# creating fixed geometry of the
# tkinter window with dimensions 150x200
root.geometry('200x150 + 400 + 300')
  
# Create Button and add some text
button = Button(root, text = 'Geeks')
button.pack(side = TOP, pady = 5)
  
# Execute Tkinter
root.mainloop()

输出:

不使用几何方法3的Tkinter窗口

运行应用程序时,您会观察到位置和大小都发生了变化。现在 Tkinter 窗口出现在不同的位置(在 Y 轴上移动了 300,在 X 轴上移动了 400)。
注意:我们也可以在几何方法中传递一个变量参数,但它应该是(variable1) x (variable2)的形式;否则,它将引发错误。