Tkinter“地方”几何管理器无法正常工作

时间:2015-03-17 15:02:56

标签: python tkinter tkinter-layout

我从电子书中学习Python。现在我正在学习Tkinter模块

本书建议运行以下代码。但是,它不能正常工作。有什么想法吗?

from Tkinter import *

window = Tk()
window.geometry("200x200")

my_frame = Frame()
my_frame.pack

button1 = Button(my_frame, text = "I am at (100x150)")
button1.place(x=100, y=150)

button2 = Button(my_frame, text = "I am at (0 x 0)")
button2.place(x=0, y=0, width=100, height=50)

window.mainloop()

我应该得到什么:

The ideal result

我得到了什么:

The actual result

添加button1.pack()button2.pack()后,我明白了:

The result with a different geometry manager

5 个答案:

答案 0 :(得分:4)

  1. 请勿使用place。学习使用packgrid。由place管理的窗口小部件不会影响其包含父级的大小。因为您没有给my_frame一个大小,并且因为您没有打包它以使其填充窗口,所以它只有1像素高,一个像素宽。这使它(及其内部的小部件)有效地不可见。如果您坚持使用place,则需要提供my_frame大小,或者将其打包以使其填充其父级。
  2. my_frame.pack应为my_frame.pack()(请注意尾随括号)
  3. 如果您对快速修复而不是解释更感兴趣,请像这样打包my_frame

    my_frame.pack(fill="both", expand=True)
    

    这就是修复代码所需的全部内容。

答案 1 :(得分:2)

我可以使代码工作的最小变化是这样的:

如果你打算使用Frame,你需要给它一个像这样的大小:

from Tkinter import *

window = Tk()
window.geometry("300x300")

# Note the change to this line
my_frame = Frame(window, width=300, height=300) 
my_frame.pack() # Note the parentheses added here

button1 = Button(my_frame, text="I am at (100x150)")
button1.place(x=100, y=150)

button2 = Button(my_frame, text="I am at (0 x 0)")
button2.place(x=0, y=0, width=100, height=50)

window.mainloop()

此外,pack()必须是函数调用,因此请添加括号

答案 2 :(得分:1)

你忘了调用myframe.pack函数 - 你只需要放置函数 在那里命名,这是有效的陈述,但框架没有“打包”到 window(我还添加了填充和展开以使框架填满整个窗口,否则放置不起作用)。 这应该有效:

from Tkinter import *

window = Tk()
window.geometry("200x200")

my_frame = Frame(window)
my_frame.pack(fill=BOTH, expand=True)

button1 = Button(my_frame, text = "I am at (100x150)")
button1.place(x=100, y=150)

button2 = Button(my_frame, text = "I am at (0 x 0)")
button2.place(x=0, y=0, width=100, height=50)

window.mainloop()

答案 3 :(得分:0)

问题似乎是您在框架上使用pack,在小部件上使用place。你不应该混合Tkinter布局管理器;使用pack grid place

如果您使用place作为小部件,则frame.pack不知道制作框架的大小。您必须手动提供框架的大小以适合其所有小部件,方法是使用构造函数中的widthheight参数,或使用frame.place,例如。

root = Tk()
root.geometry("300x300")

frame = Frame(root)
frame.place(width=200, height=200)

button1 = Button(frame, text = "I am at (100x150)")
button1.place(x=100, y=150)

button2 = Button(frame, text = "I am at (0 x 0)")
button2.place(x=0, y=0, width=100, height=50)

root.mainloop()

但正如其他人已经注意到的那样,我根本不会使用place,而是切换到gridpack。这样,框架的大小将自动适应所有内容。

答案 4 :(得分:-1)

您的按钮被放置在框架my_frame内,但由于my_frame.pack之后缺少括号,因此框架本身未显示在屏幕上。此外,框架本身的大小应在括号中指示,并且大到足以包含按钮

此外,您不能将地点用于一个小部件并打包另一个小部件,放置系统必须在整个代码中保持一致。 以下是编辑后的代码:

from Tkinter import *

window = Tk()
window.geometry("200x200")

my_frame = Frame(window)
my_frame.place(x=0, y=0, width=200, height=200)

button1 = Button(my_frame, text = "I am at (100x150)")
button1.place(x=100, y=150, width=100, height=50)

button2 = Button(my_frame, text = "I am at (0 x 0)")
button2.place(x=0, y=0, width=100, height=50)

window.mainloop()