2016-11-07 43 views
1

我建立Tkinter的应用程序,我使用一些ttk部件,包括Combobox。我需要获得combobox的状态才能执行某些操作。但是,当我尝试获得状态时,它给了我一些奇怪的东西。如何检索组合框状态

这是从print(self.combobox["state"], DISABLED)命令输出:

(<index object at 0x1f72c30>, 'disabled') 

其中DISABLED是从Tkinter变量。

我还尝试了使用self.combobox.state()状态,但输出是一样的。

注:I可使用self.combobox["state"] = NORMALself.combobox["state"] = DISABLED改变combobox状态(I可以看到,combobox是白/灰当我改变状态)。

+0

'self.combobox [ '状态'] string' – furas

回答

1

您可以使用dir()来查看哪些方法和属性具有对象。

print(dir(self.combobox['state'])) 

结果

['__class__', '__cmp__', '__delattr__', '__doc__', '__format__', 
'__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', 
'__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', 
'__subclasshook__', '__unicode__', 'string', 'typename'] 

你可以看到string(方法或属性)

如果检查

print(self.combobox['state'].string == tk.NORMAL) 

True

str()工程太

print(str(self.combobox['state']) == tk.NORMAL) 

编辑:测试最小的工作,例如:

try: 
    # Python 2 
    import Tkinter as tk 
    import ttk 
except: 
    # Python 3 
    import tkinter as tk 
    import tkinter.ttk as ttk 

root = tk.Tk() 

c = ttk.Combobox(root) 
c.pack() 

print(c['state'], c['state'] == tk.NORMAL) 

print('normal:', c['state'].string == tk.NORMAL, str(c['state']) == tk.NORMAL) 
print('disabled:', c['state'].string == tk.DISABLED, str(c['state']) == tk.DISABLED) 

c['state'] = tk.DISABLED 

print('normal:', c['state'].string == tk.NORMAL, str(c['state']) == tk.NORMAL) 
print('disabled:', c['state'].string == tk.DISABLED, str(c['state']) == tk.DISABLED) 

root.mainloop() 
+0

感谢您的回答。我还发现'self.combobox.instate([DISABLED,])'会返回'True'或'False'。请注意,这里的参数必须是状态列表。 – Fejs