仅在一侧为tkinter小部件添加内边距

123 投票
3 回答
228998 浏览
提问于 2025-04-16 07:02

我该如何给一个tkinter窗口添加内边距,而不让tkinter把控件居中呢?

 self.canvas_l = Label(self.master, text="choose a color:", font="helvetica 12")
 self.canvas_l.grid(row=9, column=1, sticky=S, ipady=30)

还有

 self.canvas_l = Label(self.master, text="choose a color:", font="helvetica 12")
 self.canvas_l.grid(row=9, column=1, rowspan=2, sticky=S, pady=30)

我只想在标签的顶部加30像素的内边距。

3 个回答

4
-pady {10,0}

这样你就是在设置上面的内边距为10,下面的内边距为0。

在Python代码中,这可能看起来像这样:

l = Label(root, text="hello" )
l.pack(pady=(10, 0)) 
9

有很多方法可以做到这一点,你可以使用 placegrid,甚至是 pack 方法。

下面是一个示例代码:

from tkinter import *
root = Tk()

l = Label(root, text="hello" )
l.pack(padx=6, pady=4) # where padx and pady represent the x and y axis respectively
# well you can also use side=LEFT inside the pack method of the label widget.

如果你想根据列和行来放置一个小部件,可以使用 grid 方法:

but = Button(root, text="hello" )
but.grid(row=0, column=1)
293

在使用 gridpack 方法时,padxpady 这两个选项可以接受一个二元组,这个二元组用来表示左右和上下的间距。

下面是一个例子:

import tkinter as tk

class MyApp():
    def __init__(self):
        self.root = tk.Tk()
        l1 = tk.Label(self.root, text="Hello")
        l2 = tk.Label(self.root, text="World")
        l1.grid(row=0, column=0, padx=(100, 10))
        l2.grid(row=1, column=0, padx=(10, 100)) 

app = MyApp()
app.root.mainloop()

撰写回答