Python 在Tkinter上进行主循环时,如何考虑对象的重新创建?
将变量分配给任何类的对象并启动Tkinter mainloop()时,使用该对象方法的“我的按钮”似乎总是使用创建的第一个对象,即使成功地将变量替换为该类的新对象 在tkinter界面上调用相同的函数时没有按钮,但在shell中也能很好地工作,但是在变量上执行方法的按钮似乎没有考虑分配给变量的新对象Python 在Tkinter上进行主循环时,如何考虑对象的重新创建?,python,class,object,tkinter,Python,Class,Object,Tkinter,将变量分配给任何类的对象并启动Tkinter mainloop()时,使用该对象方法的“我的按钮”似乎总是使用创建的第一个对象,即使成功地将变量替换为该类的新对象 在tkinter界面上调用相同的函数时没有按钮,但在shell中也能很好地工作,但是在变量上执行方法的按钮似乎没有考虑分配给变量的新对象 from tkinter import * class test(): def __init__(self): print('Object id in init is: '
from tkinter import *
class test():
def __init__(self):
print('Object id in init is: ', id(self))
def method(self):
print('Object id in his method is: ',id(self))
print('We start with a new object defined in main')
obj=test()
def new():
print('Replacing the object with a new object')
global obj
obj=test()
return
def display():
print('Object id in main is: ',id(obj))
return
root=Tk()
frame=Frame(root)
frame.pack()
n=Button(frame, text='new obj', command=new)
n.pack()
p=Button(frame, text='print_id_obj', command = display)
p.pack()
m=Button(frame, text='obj.method', command = obj.method)
m.pack()
root.mainloop()
当点击按钮p
然后点击m
时,我的对象首先有一个好的id(这是完全正常的),但当点击n
创建一个新对象时,首先会显示一个新的id,这要归功于\uu init\uuuu
功能,然后当点击p
时,我也有一个好的新id,但是,当单击m
时,显示的id是此时应已删除的第一个对象之一,就好像按钮方法定义存储了分配给var
的第一个对象,只要mainloop()
运行,单击时就会继续使用它
当关闭
tkinter
窗口并在shell中键入var.method()
时,我再次获得了良好的新id,以及在不使用tkinter
的情况下直接在shell中手动执行此操作序列时,我有3倍于我的第一个id,然后是3倍于我的新id,这是我在单击按钮时所期望的。如果您不理解,请尝试我的代码,看看我的意思。将命令更改为m=Button(frame,text='obj.method',command=lambda:obj.method())
,它将创建一个lambda
函数,在调用时使用obj
的当前值。按照您的方式,创建按钮时的值始终被使用。非常有效,谢谢。将命令更改为m=Button(frame,text='obj.method',command=lambda:obj.method())
,它将创建一个lambda
函数,在调用时使用obj
的当前值。按照您的方式,创建按钮时的值始终被使用。非常有效,谢谢。