Python variadic memorandum when inheriting a defined class

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. Check.png 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

Python variadic memorandum when inheriting a defined class
A memorandum when writing experimental code ~ Logging in python
A memorandum about correlation [Python]
A memorandum about Python mock
[GCP] A memorandum when running a Python program on Cloud Functions
A memorandum when using beautiful soup
How to write a Python class
Precautions when inheriting the DatasetMixin class
[Python] A memorandum of beautiful soup4
Precautions when creating a Python generator
[Python] Inherit a class with class variables
When writing a program in Python
Generate a first class collection in Python
Create a Python function decorator with Class
Python memorandum
Build a blockchain with Python ① Create a class
Precautions when pickling a function in python
[Python] How to make a class iterable
Python memorandum
python memorandum
python memorandum
Generate a class from a string in Python
Python memorandum
python memorandum
Python memorandum
A memorandum of python string deletion process
A memorandum of trouble when formatting data
Error when installing a module with Python pip
[Python / Tkinter] A class that creates a scrollable Frame
A memorandum of calling Python from Common Lisp
I wrote a class in Python3 and Java
[Note] Create a one-line timezone class with python
A memorandum of extraction by python bs4 request
Python: Prepare a serializer for the class instance:
Python Note: When assigning a value to a string
A memo when creating a python environment with miniconda
A memorandum for touching python Flask on heroku
Python: Create a class that supports unpacked assignment
A memorandum about the Python tesseract wrapper library
Trap trapped when running a Python Windows executable
A story when a Python user passes a JSON file
[Python] class, instance
Python basics memorandum
"Kanrika" python class
Python pathlib memorandum
Python memorandum (algorithm)
About python, class
A memo when checking whether the specified key exists in the defined dictionary with python
Python memorandum [links]
Python class, instance
#Python basics (class)
[Grasshopper] When creating a data tree on Python script
I want to generate a UUID quickly (memorandum) ~ Python ~
A python implementation of the Bayesian linear regression class
A memorandum to run a python script in a bat file
Problems when creating a csv-json conversion tool with python
Things to note when initializing a list in Python
What's in that variable (when running a Python script)
Use communicate () when receiving output in a Python subprocess
A memorandum when an error occurs with pip install
conda memorandum: Building a Python environment with supercomputer ITO