【问题标题】:Python tkinter placing a button in a grid inside a frame freezes on executionPython tkinter 在框架内的网格中放置一个按钮在执行时冻结
【发布时间】:2018-12-18 05:20:23
【问题描述】:

我使用 Tkinter 创建了两个框架。在其中一个框架中,我尝试使用网格添加一个按钮。当我运行程序时,没有输出。相反,它只是冻结了,我必须终止该进程。

代码如下:

from Tkinter import *
window=Tk()
window.title("calculator")
window.geometry("500x500")
window.resizable(0,0)

input_field=StringVar()
display_frame=Frame(window).pack(side="top")
button_frame=Frame(window).pack(side="bottom")

text=Entry(display_frame,font=('arial',20,'bold'),textvariable=input_field,justify="right").pack(fill="x",ipady=10)
clear_button=Button(button_frame,text="C").grid(row=0)
window.mainloop()

但是,如果我将 clear_button 变量更改为

clear_button=Button(button_frame,text="C").pack()

我得到一个输出。我在这里错过了什么?

【问题讨论】:

    标签: python button tkinter


    【解决方案1】:

    您不能在同一个容器(框架/窗口)中混合使用 gridpack

    也就是说你应该意识到你的 display_framebutton_frame 变量实际上是None!为什么,因为Frame(Window) 将返回一个 Frame 对象,但您在其返回值为 None 之后应用了 pack() 函数。

    所以基本上,您创建的EntryButton 小部件具有master=None,这意味着它们不在您定义的框架内,而实际上是主窗口的一部分。

    现在您可以很容易地看到为什么clear_button=Button(button_frame,text="C").pack() 正在工作,因为现在主窗口只有一个几何管理器,即 pack

    这是工作代码。

    from tkinter import * # "Tkinter" on python 2
    window=Tk()
    window.title("calculator")
    window.geometry("500x500")
    window.resizable(0,0)
    
    input_field=StringVar()
    display_frame=Frame(window)
    display_frame.pack(side="top")
    button_frame=Frame(window)
    button_frame.pack(side="bottom")
    
    Entry(display_frame,font=('arial',20,'bold'),textvariable=input_field,justify="right").pack(fill="x",ipady=10)
    Button(button_frame, text="C").grid(row=0)
    window.mainloop()
    

    【讨论】:

    • 你成就了我的一天!!
    【解决方案2】:

    您不能在具有相同主控的小部件上同时使用 gridpack 方法。

    这里,跟随下面的线程进行详细了解:

    python pack() and grid() methods together

    【讨论】:

    猜你喜欢
    • 2018-05-05
    • 1970-01-01
    • 2022-10-23
    • 2018-06-11
    • 1970-01-01
    • 2018-05-11
    • 2021-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多