Search code examples
pythontkinter

Looking for Short and better way to create widget in Tkinter


I am using Python 3.11.9 in windows 11 OS (home edition)
I create text entry using three lines shown in code below:

import tkinter as tk
class Application(tk.Tk):
    def __init__(self, title:str="Bill generation", x:int=0, y:int=0, **kwargs):
            tk.Tk.__init__(self)
        
            self.default_txt_for_desc=tk.StringVar()
            self.default_txt_for_desc.set("PCS")
            self.txt_desc=tk.Entry(self,width=10,textvariable=self.default_txt_for_desc)
            self.txt_desc.grid(column=0,row=0)
            self.update_idletasks()
            self.state('zoomed')
        
if __name__ == "__main__":
            Application(title="Bill printing app").mainloop()

How can I do that in one line?


Solution

  • You can compress this code into this line:

    (self.txt_desc := tk.Entry(self, width=10, textvariable=(self.default_txt_for_desc := tk.StringVar()).set("PCS") and None or self.default_txt_for_desc).grid(row=0, column=0)
    

    This creates the Entry self.txt_desc and the StringVar self.default_txt_for_desc. It uses the walrus operator := to assign the variables. This allows multiple assignments and further operations on the objects.

    Although this is short (in the sense if the amount of lines), it is not readable and much worse than your version. A short way is not necessarily better. The line can easily lead to confusion later on.

    The PEP 8 guidelines for example require you to have a maximum line length of 79 characters. This limit should allow the code to be read on most computer displays without horizontal scrolling.

    Instead of collecting sections in one line, you can make use of functions and modules for such pieces, to organise your code.

    Also note that having more code in one line will not perform necessarily any better in terms of speed. Even if there is a performance advantage, it is overshadowed by readability.