【问题标题】:Checkbutton always returns TrueCheckbutton 总是返回 True
【发布时间】:2017-03-18 18:22:29
【问题描述】:

同志们, 我在使用 tkinter 库时遇到了问题。 这是一个代码:

from tkinter import *
root = Tk()
class Doc_Search:      
    def __init__(self, master = None):
        self.var6 = IntVar()
        self.var7 = IntVar()
#Winglets checkbuttons
        self.C2 = Checkbutton(self.labelframeA, variable = self.var6, offvalue = 0, onvalue = 1, command = self.onWinglets)
        self.C2.grid(row=2, column=3, sticky = 'W')

        self.R9 = Radiobutton(self.labelframeA, text = "Blended", state=DISABLED, variable = self.var7, value = 1, command = self.Wing_key)
        self.R9.grid(row=3, column=3, sticky='W')

        self.R10 = Radiobutton(self.labelframeA, text = "SSW", state=DISABLED, variable = self.var7, value = 2, command = self.Wing_key)
        self.R10.grid(row=4, column=3, sticky='W'+'N')

    def onWinglets(self):
               self.key5 = self.var6.get()
               if self.key5:
                  self.R9['state']='normal'
                  self.R10['state']='normal'
                  return True
               else:
                  self.var7.set(0)
                  self.R9['state']='disabled'
                  self.R10['state']='disabled'
                  return False
        myapp = Doc_Search(root)
        root.mainloop()

下一个函数,取决于onWinglets(self)

    def Wing_key(self): 
        if self.onWinglets:

就像onWinglets(self) 总是返回True 一样工作(不管Checkbutton 是否被按下)。这有点奇怪。谁能帮助解决这个问题?非常感谢!

PS:我尝试检查onWinglets(self)函数的性能为:

z = myapp.onWinglets()
print(z)

输出如下:

Traceback (most recent call last):
  File "windows_tk_1.py", line 313, in <module>
    z = myapp.onWinglets()
  File "windows_tk_1.py", line 220, in onWinglets
    self.R9['state']='normal'
  File "/usr/lib/python3.5/tkinter/__init__.py", line 1340, in __setitem__
    self.configure({key: value})
  File "/usr/lib/python3.5/tkinter/__init__.py", line 1333, in configure
    return self._configure('configure', cnf, kw)
  File "/usr/lib/python3.5/tkinter/__init__.py", line 1324, in _configure
    self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: invalid command name ".139943983318912.139943983320312"

感谢大家的帮助!

【问题讨论】:

    标签: python-3.x tkinter boolean


    【解决方案1】:

    尝试将您的条件重写为:

    if self.var6.get() == 1 :
    

    也许您误解了self.key5 = self.var6.get() 不会将IntVar() 值转换为布尔指标。直接测试var6.get()即可。

    随意将测试值更改为0

    【讨论】:

    • 我做了以下(在第二个函数中):def Wing_key(self): if self.var6.get() == 1: 看起来它有效。谢谢!
    猜你喜欢
    • 2013-08-06
    • 2017-05-10
    • 2013-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多