如何仅在一侧向 tkinter 小部件添加填充?
在本文中,我们将讨论仅在一侧向 Tkinter 小部件添加填充的过程。在这里,我们创建一个小部件并使用 tkinter 中的 widget.grid() 方法来填充小部件的内容。例如,让我们创建一个标签并使用 label.grid() 方法。下面给出了语法:
label1 = Widget_Name(app, text="text_to_be_written_in_label")
label1.grid(
padx=(padding_from_left_side, padding_from_right_side),
pady=(padding_from_top, padding_from_bottom))
所需步骤:
- 首先,导入库tkinter
from tkinter import *
- 现在,使用 tkinter 创建一个 GUI 应用程序
app= Tk()
- 接下来,为应用程序命名。
app.title(“Name of GUI app”)
- 然后,通过将#Widget Name替换为小部件的名称(例如标签、按钮等)来创建小部件。
l1 =Widget_Name(app, text="Text we want to give in widget")
- 此外,在我们想要给它的地方提供填充。
l1.grid(padx=(padding from left side, padding from right side),
pady=(padding from top, padding from bottom))
- 例如,如果我们只想从顶部给出填充,则在指定位置输入填充值,其余的为零。它将仅从一侧(即顶部)为小部件提供填充。
l1.grid(padx=(0, 0), pady=(200, 0))
- 最后,制作用于在屏幕上显示 GUI 应用程序的循环。
app.mainloop( )
- 它将给出如下输出:
示例 1:在小部件的左侧填充
Python
# Python program to add padding
# to a widget only on left-side
# Import the library tkinter
from tkinter import *
# Create a GUI app
app = Tk()
# Give title to your GUI app
app.title("Vinayak App")
# Maximize the window screen
width = app.winfo_screenwidth()
height = app.winfo_screenheight()
app.geometry("%dx%d" % (width, height))
# Construct the label in your app
l1 = Label(app, text='Geeks For Geeks')
# Give the leftmost padding
l1.grid(padx=(200, 0), pady=(0, 0))
# Make the loop for displaying app
app.mainloop()
Python
# Python program to add padding
# to a widget only from top
# Import the library tkinter
from tkinter import *
# Create a GUI app
app = Tk()
# Give title to your GUI app
app.title("Vinayak App")
# Maximize the window screen
width = app.winfo_screenwidth()
height = app.winfo_screenheight()
app.geometry("%dx%d" % (width, height))
# Construct the button in your app
b1 = Button(app, text='Click Here!')
# Give the topmost padding
b1.grid(padx=(0, 0), pady=(200, 0))
# Make the loop for displaying app
app.mainloop()
输出:
示例 2:从顶部填充到小部件
Python
# Python program to add padding
# to a widget only from top
# Import the library tkinter
from tkinter import *
# Create a GUI app
app = Tk()
# Give title to your GUI app
app.title("Vinayak App")
# Maximize the window screen
width = app.winfo_screenwidth()
height = app.winfo_screenheight()
app.geometry("%dx%d" % (width, height))
# Construct the button in your app
b1 = Button(app, text='Click Here!')
# Give the topmost padding
b1.grid(padx=(0, 0), pady=(200, 0))
# Make the loop for displaying app
app.mainloop()
输出: