为什么在添加按钮后调节 tk canvas 大小的关键参数不起作用?
why do the key arguments that regulate the size of a tk canvas fail to work after a button is added?
我试图构建一个 window 足够大,其中包含一些小部件。所以我传递了一些关键参数来调节 canvas 的大小并且它按预期工作。但是,当我在 canvas 中添加一个按钮时,window 返回到它原来的小尺寸(可能是默认尺寸)。
我在代码最后测试了width of height的值:
print(window["width"]) 给出 700
print(window["height"]) 给出 800
这让我更加困惑,因为如果 width 和 height 属性具有我输入的值,为什么添加按钮会阻止 window 显示这些属性?
import tkinter as tk
root=tk.Tk()
window=tk.Canvas(root,width=700,height=800)
window.pack()
button=tk.Button(window,text="test button") #(1)
button.pack()#(2)
# the Canvas shows the wanted size when (1) and (2)is deleted
root.mainloop()
Canvas
或 Frame
将在 widget
被打包或网格化后缩小到所需的大小。但是你可以通过 propagate
明确告诉它不要:
window=tk.Canvas(root,width=700,height=800)
window.pack()
window.propagate(0)
或者,您可以在 Button
小部件上使用 place
方法:
button.place(relx=0.5,rely=0.5)
我试图构建一个 window 足够大,其中包含一些小部件。所以我传递了一些关键参数来调节 canvas 的大小并且它按预期工作。但是,当我在 canvas 中添加一个按钮时,window 返回到它原来的小尺寸(可能是默认尺寸)。
我在代码最后测试了width of height的值: print(window["width"]) 给出 700 print(window["height"]) 给出 800
这让我更加困惑,因为如果 width 和 height 属性具有我输入的值,为什么添加按钮会阻止 window 显示这些属性?
import tkinter as tk
root=tk.Tk()
window=tk.Canvas(root,width=700,height=800)
window.pack()
button=tk.Button(window,text="test button") #(1)
button.pack()#(2)
# the Canvas shows the wanted size when (1) and (2)is deleted
root.mainloop()
Canvas
或 Frame
将在 widget
被打包或网格化后缩小到所需的大小。但是你可以通过 propagate
明确告诉它不要:
window=tk.Canvas(root,width=700,height=800)
window.pack()
window.propagate(0)
或者,您可以在 Button
小部件上使用 place
方法:
button.place(relx=0.5,rely=0.5)