When writing a program using Python GUI (Tkinter), when inheriting GUI Class Variadic arguments are also inherited without exception. However, if you add an argument in the inherited Class, an error will occur in the inherited source and it will be difficult to use.
For example, Tkinter's Checkbutton cannot be set to its default value. A memorandum when creating a Check button that allows you to set the initial value.
If you write it normally, it will be as follows.
NormalCheckbox
cv = tk.BooleanVar()
cb = tk.Checkbutton(self, parent, variable=cv)
cv.set(True) #Initial value setting
But I want to write it like this.
ShimplCheckbox
cb = tk.Checkbutton(self, parent, check=True)
So, let's make SimpleCheck by inheriting tk.Checkbutton.
SimpleCheckbox.py
# Initial value = check=True or False
class SimpleCheck(tk.Checkbutton):
def __init__(self, parent, *args, **kw):
self.flag = kw.pop('check')
self.var = tk.BooleanVar()
if self.flag:
self.var.set(True)
self.txt = kw["text"]
tk.Checkbutton.__init__(self, parent, *args, **kw, variable=self.var)
def get(self):
return self.var.get()
However, there is a problem with this code. The problem is that if you don't specify the argument "check", you'll get an error.
mainloop
if __name__ == '__main__':
app = tk.Tk()
sc1 = SimpleCheck(app, check=True, text="hoge")
sc1.pack()
sc2 = SimpleCheck(app)
sc2.pack()
print(sc1.getText())
print(sc1.cget('text'))#same result
app.mainloop()
error
Traceback (most recent call last):
File "arg_test.py", line 24, in <module>
sc2 = SimpleCheck(app)
File "arg_test.py", line 7, in __init__
self.flag = kw.pop('check')
KeyError: 'check'
Therefore, the method of extracting arguments in inheritance using variable arguments is shown as a memorandum. When using the ternary operator, using "pass" seems to give an error.
SimpleCheck.py
import tkinter as tk
# Check value :check=True or False (Default False)
# Label text :text=Keword
class SimpleCheck(tk.Checkbutton):
def __init__(self, parent, *args, **kw):
self.flag = kw.pop('check') if('check' in kw) else False
self.txt = kw['text'] if('text' in kw) else ""
self.var = tk.BooleanVar()
if self.flag:
self.var.set(True)
tk.Checkbutton.__init__(self, parent, *args, **kw, variable=self.var)
def get(self):
return self.var.get()
def getText(self):
return self.txt
if __name__ == '__main__':
app = tk.Tk()
sc1 = SimpleCheck(app, check=True, text="hoge")
sc1.pack()
sc2 = SimpleCheck(app)
sc2.pack()
print(sc1.getText())
print(sc1.cget('text'))#same result
app.mainloop()
Postscript @shiracamus gave me some advice It seems that the initial value can be set with the pop second argument of Dic without using the ternary operator. Thank you for your advice.
diff
def __init__(self, parent, *args, **kw):
self.flag = kw.pop('check', False)
self.txt = kw['text'] if('text' in kw) else ""
Recommended Posts