简体   繁体   English

我想获得 Entrybox 和 Checkbutton 的值,但我什么也没得到,为什么? (我是 tkinter 的新手)

[英]I want to get value of Entrybox and Checkbutton but I get nothing why? (I am new to tkinter)

I want to get value of Entrybox and Checkbutton but I get nothing why?我想获得 Entrybox 和 Checkbutton 的值,但我什么也没得到,为什么? (I am new to tkinter) (我是 tkinter 的新手)

from tkinter import *

def m1():
    m1 = Tk()
    entry_val = StringVar()
    check_val = IntVar()
    Entry(m1, textvariable=entry_val).pack()
    Checkbutton(m1, text='CheckButton', variable=check_val).pack()

    def show():
        print(entry_val.get())
        print(check_val.get())

    Button(m1, text='click!', command=show).pack()
    m1.mainloop()


def main():
    main = Tk()

    Button(main, text='click! (main)', command=m1).pack()
    main.mainloop()


main()

The short and simple answer:简短的回答:

In your code you need to change m1 = Tk() to m1 = Toplevel() .在您的代码中,您需要将m1 = Tk()更改为m1 = Toplevel() This will fix your issue.这将解决您的问题。

The long answer:长答案:

When writing a Tkinter GUI 99.99% of the time you are only ever going to use 1 tkinter instance Tk() .在编写 Tkinter GUI 时,99.99% 的时间你只会使用 1 个 tkinter 实例Tk() The reason for this is that each instance of Tk() is contained within its own personal "Sandbox".这样做的原因是每个Tk()实例都包含在它自己的个人“沙箱”中。 Meaning it cannot play with others.这意味着它不能与其他人一起玩。 So one instance of Tk() cannot communicate with a separate Tk() instance.因此,一个Tk() () 实例无法与单独的Tk()实例通信。

It is my understanding that if you do not specify what instance a method belongs to within the method then it will default to the 1st instance of Tk() .我的理解是,如果您没有在方法中指定方法属于哪个实例,那么它将默认为Tk()的第一个实例。 So the StringVar() and IntVar() you have create cannot be printed due to them belonging to main .因此,您创建的StringVar()IntVar()无法打印,因为它们属于main Because main cannot talk to m1 you cannot update this value.因为main无法与m1对话,所以您无法更新此值。

We can actually test this if you change:如果您更改,我们实际上可以对此进行测试:

entry_val = StringVar()
check_val = IntVar()

To:至:

entry_val = StringVar(m1)
check_val = IntVar(m1)

You will see your variables update properly.您将看到您的变量正确更新。

Or if you change m1 = Tk() to m1 = Toplevel() (the correct solution) you will see that everything works as needed.或者,如果您将m1 = Tk()更改为m1 = Toplevel() (正确的解决方案),您将看到一切都按需要工作。

Toplevel() is specifically designed for creating new windows in tkinter so everything can stay in the same "Sandbox" and work together. Toplevel()专为在 tkinter 中创建新的 windows 而设计,因此一切都可以留在同一个“沙箱”中并一起工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM