【问题标题】:Pack manager of tkinter in pythonpython中tkinter的包管理器
【发布时间】:2017-08-31 09:29:15
【问题描述】:

我在 python 2.7 中编写了这段代码,并且在这段代码中使用了“pack_propagate”。第一次“pack_propagate”工作正常,但是当我点击按钮 1 时,“pack_propagate”不起作用。谁能告诉我原因?

from tkinter import *

root = Tk()
root.title("pack_forget check")

tk_window_width = 500
tk_window_height = 300
screen_width = root.winfo_screenwidth() # width of the screen
screen_height = root.winfo_screenheight() # height of the screen
x = (screen_width/2) - (tk_window_width/2)
y = (screen_height/2) - (tk_window_height/2)
root.geometry('%dx%d+%d+%d' %(tk_window_width, tk_window_height, x, y))

frame1 = Frame(root, bg="red", height=250, width=250)
frame2 = Frame(root, bg="green", height=250, width=250)

def first():
    frame1.pack(side=TOP, padx=20, pady=20)
    frame1.pack_propagate(0)
    frame2.pack_forget()

def second():
    frame2.pack(side=TOP, padx=20, pady=20)
    frame2.pack_propagate(0)
    frame1.pack_forget()   

label1 = Label(frame1, text="Frame 1")
label1.pack(side="top")
button1 = Button(frame1, text="button 1", command=second, width=10)
button1.pack(side="bottom")

label2 = Label(frame2, text="Frame 2")
label2.pack(side="top")
button2 = Button(frame2, text="button 2", command=first, width=10)
button2.pack(side="bottom")

frame1.pack(side=TOP, padx=20, pady=20)
frame1.pack_propagate(0)

root.mainloop()

【问题讨论】:

  • @AnupamYadav “工作不正常”是什么意思?您预计会发生什么以及正在发生什么?
  • "pack_propagate" 不会缩小框架。第一次 frame1 没有因为 pack_propagate 而缩小,但是在单击“button1”后,当第二帧出现时,即使我也将“pack_propagate”用于第二帧,它也不会跟随“pack_propagate”。
  • @AnupamYadav 好的,目前,当我按下button 1 时,没有出现绿框,您打算出现绿框吗?
  • 是的,亲爱的。 @officialaimm
  • 调用pack_propagate 很少能正确解决问题。如果你能更好地描述你真正想要完成的事情,我们可以想出一些更好的想法。

标签: python python-2.7 python-3.x tkinter


【解决方案1】:

在mainloop()之前加上这个,好像可以解决问题了。老实说,我不确定它是如何工作的,但看起来确实如此。我看到你用frame1 做到了,我想:嘿,为什么不frame2? :D

frame2.pack(side=TOP, padx=20, pady=20)
frame2.pack_propagate(0)

root.mainloop()

【讨论】:

  • 谢谢。它的工作。我在函数中添加了“pack_propagate”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-10
  • 2021-05-20
  • 2017-12-24
  • 1970-01-01
  • 2020-02-15
  • 2019-05-05
  • 1970-01-01
相关资源
最近更新 更多