【发布时间】:2019-06-02 22:01:52
【问题描述】:
我有一个使用 Tkinter 的 GUI,它有一个主屏幕,然后当您按下按钮时会出现一个弹出窗口,您可以在其中选择一个复选按钮,然后会向您发送一封电子邮件。
无论我做什么,我都无法将检查按钮的值读取为 1 或 True 它始终 = 0 或 False。
这是我的代码:
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 - Can't make tkinter checkbutton work normally when running as script Self.CheckVar1 - TKInter checkbox variable is always 0 只有一个 mainloop() 实例 - Python tkinter checkbutton value always equal to 0
我也检查了非常相似的问题,但我不打算全部发布。
感谢任何帮助。
【问题讨论】:
-
您是否尝试使用
BooleanVar()而不是IntVar()?查看类似问题:stackoverflow.com/q/43970664/3991125 -
@albert 是的,我已经尝试过
BooleanVar(),但我总是得到False -
BIG NO GO,您使用
tk.Tk的次数超过一次。这会导致意外行为。将class PopUp(tk.Tk):更改为class PopUp(tk.Toplevel): -
@stovfl 谢谢,这就是问题所在。现在完美运行。还将
CheckVar1移入课堂