pythonpython-3.xtkinter

How to reset StringVar in tkinter


I am currently working on a calculator and I was coding the C Button (the C button is the button that erases the current operation).

My idea was to make the C Button return all variables used during the operation to their starting state so we can start a new operation after pressing C.

The problem is there is something called StringVar() in Tkinter that I used after reading an answer on StackOverflow. It is used to update the label every time I hit a new Button.

It works but when trying to return it to its normal state when pressing the C button it doesn't work. They are still the same. so how can I reset the StringVar?

Solution: Turns out I didn't assign the global variables used in the function, but any way to reset the stringVar you can just do this: (variable name).set("")


Solution

  • It should be variableName.set("")

    s = StringVar()
    
    # here getting textvariable
    
    value = s.get()
    print(value)  # input value
    
    s.set("")  # reset it
    

    Edit: After below comment, I am adding this structure to show how to keep desired item clean

    # getting input
    sFaculty = StringVar()
    combo = ttk.Combobox(tab1, ..., textvariable=sFaculty, ...)
    
    # assing it to function
    Button(tab1, text="Insert", command=lambda: guiActions.insertStudent(..., sFaculty, ...))
    
    # process and clean in a function
    def insertStudent(..., faculty, ...):
    
        # process here
    
        # cleaning after insert
        faculty.set("")