这两天使用Python开发一个简单的界面程序,遇到了一个奇怪的问题,
代码是这样的:
try:
from tkinter import *
except ImportError: #Python 2.x
PythonVersion = 2
from Tkinter import *
import ttk
else: #Python 3.x
PythonVersion = 3
from tkinter import ttk
class VerifyFrame(ttk.Frame):
def doClean(self):
print(str(self.bcheck.get())+'--\n')
def __init__(self, parent):
ttk.Frame.__init__(self, parent)
monty = ttk.LabelFrame(self, text='Table1')
monty.grid(column=0, row=0, padx=8, pady=4)
self.bcheck = IntVar()
check2 = Checkbutton(monty, text="Enable",variable=self.bcheck,\
onvalue = 1, offvalue = 0,state='normal')
check2.grid(column=0, row=0, sticky='E')
ttk.Button(monty, text ="do", command = self.doClean).grid(column=0, row=1, sticky='E')
class MainFrame(ttk.Frame):
def __init__(self,master):
ttk.Frame.__init__(self,master)
self.t=master
self.tb=ttk.Notebook(self,height=600,width=800)
self.tb.grid(row=0,column=0)
lable=VerifyFrame(self.t)
self.tb.add(lable,text='test')
class Application(Tk):
def __init__(self):
Tk.__init__(self)
self.wm_title('Data Parser')
self.wm_geometry('800x600')
self.mainframe = MainFrame(self)
self.mainframe.pack(side="top",fill="both", expand=True)
if __name__ == '__main__':
APPLICATION_GUI = Application()
APPLICATION_GUI.mainloop()
发现无论如何选择self.bcheck的get的结果都是0,绑定变量不起作用?!
通过检查tk的代码,发现IntVar的初始化实际是:
def __init__(self, master=None, value=None, name=None):
将self.bcheck = IntVar()修改为self.bcheck = IntVar(master=self)
OK,问题解决了