Tkinter模块化类开发:StringVar赋值后Label无法显示文本求助
问题原因及解决方案
你的代码核心问题出在传递text_variable参数的方式错误:
self.var_text.set('hello tkinter')是一个方法调用,这个方法的作用是给StringVar赋值,但它没有返回值(返回None)。你把这个调用结果传给Labelcl的text_variable参数,相当于给Label绑定了None,自然无法显示文本。
修正后的代码
from tkinter import * class Maincl(Tk): def __init__(self,xwidth,yheight): super().__init__() self.geometry(f'{xwidth}x{yheight}') self.var_text=StringVar() # 先给变量赋值 self.var_text.set('hello tkinter') Labelcl(self,'darkblue',30,3).pack() # 直接传递StringVar对象给text_variable参数 Labelcl(self, 'white', 30, 3, self.var_text).pack() self.mainloop() class Labelcl(Label): def __init__(self,master,bg_color,width,height,text_variable=None): super().__init__(master) self.master=master self.configure(bg=bg_color,width=width,height=height,textvariable=text_variable) app=Maincl('500','300')
额外优化(可选)
可以把Label的配置参数直接传给父类的构造方法,减少一次configure调用,代码更简洁:
class Labelcl(Label): def __init__(self,master,bg_color,width,height,text_variable=None): super().__init__( master, bg=bg_color, width=width, height=height, textvariable=text_variable ) self.master=master
内容的提问来源于stack exchange,提问作者xlmaster
相关产品推荐
相关产品推荐

