首页 > 解决方案 > 复选框总是在弹出窗口中读取 0 - Tkinter

问题描述

我有一个使用 Tkinter 的 GUI,它有一个主屏幕,然后当您按下按钮时会出现一个弹出窗口,您可以在其中选择一个复选按钮,然后会向您发送一封电子邮件。无论我做什么,我都无法读取 checkbutton 的值,1或者True它总是 =0False

这是我的代码:

import tkinter as tk
from tkinter import *
import time
root = tk.Tk()
root.title('Status')
CheckVar1 = IntVar()
def email():
    class PopUp(tk.Tk):
        def __init__(self):
            tk.Tk.__init__(self)

            popup = tk.Toplevel(self, background='gray20')
            popup.wm_title("EMAIL")
            self.withdraw()
            popup.tkraise(self)
            topframe = Frame(popup, background='gray20')
            topframe.grid(column=0, row=0)

            bottomframe = Frame(popup, background='gray20')
            bottomframe.grid(column=0, row=1)

            self.c1 = tk.Checkbutton(topframe, text="Current", variable=CheckVar1, onvalue=1, offvalue=0, height=2, width=15, background='gray20', foreground='snow', selectcolor='gray35', activebackground='gray23', activeforeground='snow')
            self.c1.pack(side="left", fill="x", anchor=NW)           
            label = tk.Label(bottomframe, text="Please Enter Email Address", background='gray20', foreground='snow')
            label.pack(side="left", anchor=SW, fill="x", pady=10, padx=10)
            self.entry = tk.Entry(bottomframe, bd=5, width=35, background='gray35', foreground='snow')
            self.entry.pack(side="left", anchor=S, fill="x", pady=10, padx=10)
            self.button = tk.Button(bottomframe, text="OK", command=self.on_button, background='gray20', foreground='snow')
            self.button.pack(side="left", anchor=SE, padx=10, pady=10, fill="x")

        def on_button(self):
            address = self.entry.get() 
            print(address)
            state = CheckVar1.get()
            print (state)
            time.sleep(2)
            self.destroy()


    app = PopUp()
    app.update()

tk.Button(root, 
            text="EMAIL", 
            command=email, 
            background='gray15', 
            foreground='snow').pack(side=tk.BOTTOM, fill="both", anchor=N)

screen = tk.Canvas(root, width=400, height=475, background='gray15')
screen.pack(side = tk.BOTTOM, fill="both", expand=True)


def latest():
    #Other code
    root.after(300000, latest)
root.mainloop()

弹出窗口完美运行,输入时将打印电子邮件,但复选框的值始终为 0。

我努力了:

CheckVar1 = tk.IntVar()- 没有成功

self.CheckVar1& self.CheckVar1.get()- 没有成功

删除self.withdraw()- 没有成功

我在脚本中只有一个root.mainloop(),我将app.update()其用于弹出窗口,因为没有这个它不会打开。

我已经检查了这些现有问题的解决方案,但没有一个有帮助: Self.withdraw -作为脚本运行时无法使 tkinter checkbutton 正常工作 Self.CheckVar1 - TKInter 复选框变量始终为 0 只有一个 mainloop() 实例 - Python tkinter checkbutton值始终等于 0

我也检查了非常相似的问题,但我不打算全部发布。

任何帮助表示赞赏。

标签: pythontkinter

解决方案


问题是你有两个根窗口。每个根窗口都有自己的内部 tcl 解释器,一个中的小部件和 tkinter 变量对另一个完全不可见。您正在IntVar第一个根窗口中创建,然后尝试将其与第二个根窗口中的复选按钮相关联。这行不通。Tk您应该始终在 tkinter 程序中只有一个实例。


推荐阅读