我想使用這個命令來設定我的自定義變數,如何做到這一點:
self.ent1.configure(my_custom_var='teste')
我希望我的自定義變數成為 .configure 字典的一部分
示例代碼:
from tkinter import *
class My_Entry(Entry):
def __init__(self, parent, my_custom_var='', *args, **kwargs):
super().__init__(parent, *args, **kwargs)
#print('my_custom value: ', my_custom_var)
print(self['my_custom_var'])
return
def configure(self, **kwargs):
super().configure(**kwargs)
print(kwargs) #<--- my custom var here in kwargs
#--------------
class Mainframe(Tk):
def __init__(self):
Tk.__init__(self)
#self.ent1 = My_Entry(self, my_custom_var='teste')
self.ent1 = My_Entry(self)
self.ent1.configure(show='*')
#self.ent1.configure(show='*', my_custom_var='teste')
self.ent1.pack()
return
if __name__== '__main__':
app = Mainframe()
app.mainloop()
uj5u.com熱心網友回復:
Tkinter 無法添加與內置選項完全相同的選項。但是,您可以覆寫configure和cget處理自定義選項和默認選項。
這是一種方法的示例,盡管它不是唯一的方法。
class My_Entry(tk.Entry):
# tuple of supported custom option names
custom_options = ("my_custom_var",)
def __init__(self, parent, *args, my_custom_var='', **kwargs):
super().__init__(parent)
self.configure(my_custom_var=my_custom_var, **kwargs)
def configure(self, **kwargs):
for key in self.custom_options:
if key in kwargs:
setattr(self, key, kwargs.pop(key))
if kwargs:
super().configure(**kwargs)
def cget(self, key):
if key in self.custom_options:
return getattr(self, key)
else:
return super().cget(key)
這使您可以使用cget或直接訪問類屬性:
entry = My_Entry(root, width=40, my_custom_var="Hello, world")
print(f"custom var via cget: {entry.cget('my_custom_var')}")
print(f"custom var via attribute: {entry.my_custom_var}")
在課堂上,你也可以這樣做:
print(f"custom var via cget: {self.cget('my_custom_var')}")
print(f"custom var via attribute: {self.my_custom_var}")
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/402214.html
下一篇:無法從類中列印__str__
