如何在tkinter中为屏幕下半部分添加内边距

0 投票
2 回答
53 浏览
提问于 2025-04-13 20:26

我在这个窗口上用了内边距(padding),这是窗口的样子,但是你可以看到,底部没有内边距。

我试着查了一下,但没有找到什么有用的解决办法。我还尝试给按钮加内边距,但结果变成了这样。这是图片,还有这是代码

from tkinter import Tk, Canvas, PhotoImage, Label, Button

PINK = "#e2979c"
RED = "#e7305b"
GREEN = "#9bdeac"
YELLOW = "#f7f5dd"
FONT_NAME = "Courier"
workmin = 24
seconds = 59
SHORT_BREAK_MIN = 5
LONG_BREAK_MIN = 20
TIMESDONE = 0

root = Tk()
root.title(string="Pomodoro work")
root.config(padx=224, pady=100, bg=YELLOW)

canvas = Canvas(width=200, height=224, bg=YELLOW, highlightthickness=0)
tomato_png = PhotoImage(file="tomato.png")
canvas.create_image(100, 112, image=tomato_png)
canvas.create_text(100, 130, text="00.00", fill="white", font=(FONT_NAME, 35, "bold"))
logo = Label(text="Timer", fg=GREEN, bg=YELLOW, font=(FONT_NAME, 70, "bold"))
logo.pack()
times_done = Label(text="✘✘✘✘", fg=RED, bg=YELLOW, font=(FONT_NAME, 35, "bold"))
times_done.place(x=55.5, y=350)
canvas.pack()

start = Button(text="Start", font=("Courier", 20, "normal"))
start.place(x=-139, y=350)
reset = Button(text="reset", font=("Courier", 20, "normal"))
reset.place(x=250, y=350)

root.mainloop()

2 个回答

0

如果你想保留下面这行代码设置的内边距:

root.config(padx=224, pady=100, bg=YELLOW)

那么你就不要在这两个按钮和“xxxx”标签上使用 .place() 方法。可以用一个框架来装这些按钮和标签,然后在这个框架上使用 .pack() 方法。

更新后的代码:

from tkinter import Tk, Canvas, PhotoImage, Label, Button, Frame

PINK = "#e2979c"
RED = "#e7305b"
GREEN = "#9bdeac"
YELLOW = "#f7f5dd"
FONT_NAME = "Courier"
workmin = 24
seconds = 59
SHORT_BREAK_MIN = 5
LONG_BREAK_MIN = 20
TIMESDONE = 0

root = Tk()
root.title(string="Pomodoro work")
root.config(padx=224, pady=100, bg=YELLOW)

logo = Label(root, text="Timer", fg=GREEN, bg=YELLOW, font=(FONT_NAME, 70, "bold"))
logo.pack()

canvas = Canvas(root, width=200, height=224, bg=YELLOW, highlightthickness=0)
canvas.pack()

tomato_png = PhotoImage(file="tomato.png")
canvas.create_image(100, 112, image=tomato_png)
canvas.create_text(100, 130, text="00.00", fill="white", font=(FONT_NAME, 35, "bold"))

# create a frame for the two buttons and "xxxx" label
frame = Frame(root, bg=YELLOW)
frame.pack()

# create the two buttons and the label as children of frame

start = Button(frame, text="Start", font=("Courier", 20, "normal"))
start.pack(side="left")

times_done = Label(frame, text="✘✘✘✘", fg=RED, bg=YELLOW, font=(FONT_NAME, 35, "bold"))
times_done.pack(side="left", padx=100)

reset = Button(frame, text="reset", font=("Courier", 20, "normal"))
reset.pack(side="left")

root.mainloop()

另外,创建控件时,最好指定它们的父级,这样更清晰。

0

你可以(而且应该)通过 geometry 属性来设置你的主窗口的大小。

所以,不要再用 padxpady 来调整窗口的大小了:

root.config(padx=224, pady=100, bg='yellow')

你应该使用:

root.geometry('224x100')  # or whatever '<width>x<height>' you want

注意,窗口的大小

  • 必须是一个字符串
  • 格式要是 '<宽度>x<高度>',单位是像素

geometry 还有一些其他的选项,你可以在 这里 了解更多,当然你也可以和 configure 一起使用,这样就能保持黄色背景(不过你可能可以省略 padding!)

撰写回答