从按钮命令调用的函数与正常调用不同? (Python2 tkinter)
Function called from button command differs from normal call ? (Python2 tkinter)
这里我定义2 class:
from Tkinter import *
class Two:
def __init__(self):
self.main2 = Tk()
self.mainFrame2 = Frame(self.main2)
self.mainFrame2.pack()
self.x= BooleanVar()
self.cb = Checkbutton(self.mainFrame2,text='tick', variable = self.x)
self.button2 = Button(self.mainFrame2,text ='button', command = self.Command)
self.cb.pack()
self.button2.pack()
self.main2.mainloop()
def Command(self):
print self.x.get()
class One:
def __init__(self):
self.main = Tk()
self.mainFrame = Frame(self.main)
self.mainFrame.pack()
self.button = Button(self.mainFrame,text ='Ok', command = lambda: self.callTwo())
self.button.pack()
self.main.mainloop()
def callTwo(self):
Two()
当我直接调用
Two()
勾选复选框,然后点击按钮,打印 1
但如果我打电话
One()
然后单击确定,勾选复选框,单击按钮,它会打印 0
这是为什么?我想调用 One() 并让它打印 1
您不能在 tkinter 应用程序中有两个 Tk
实例。如果要创建多个 window,请创建 Toplevel
的实例。您只能有一个 Tk
实例,并且应该只调用一次 mainloop
。
这里我定义2 class:
from Tkinter import *
class Two:
def __init__(self):
self.main2 = Tk()
self.mainFrame2 = Frame(self.main2)
self.mainFrame2.pack()
self.x= BooleanVar()
self.cb = Checkbutton(self.mainFrame2,text='tick', variable = self.x)
self.button2 = Button(self.mainFrame2,text ='button', command = self.Command)
self.cb.pack()
self.button2.pack()
self.main2.mainloop()
def Command(self):
print self.x.get()
class One:
def __init__(self):
self.main = Tk()
self.mainFrame = Frame(self.main)
self.mainFrame.pack()
self.button = Button(self.mainFrame,text ='Ok', command = lambda: self.callTwo())
self.button.pack()
self.main.mainloop()
def callTwo(self):
Two()
当我直接调用
Two()
勾选复选框,然后点击按钮,打印 1
但如果我打电话
One()
然后单击确定,勾选复选框,单击按钮,它会打印 0
这是为什么?我想调用 One() 并让它打印 1
您不能在 tkinter 应用程序中有两个 Tk
实例。如果要创建多个 window,请创建 Toplevel
的实例。您只能有一个 Tk
实例,并且应该只调用一次 mainloop
。