3

I have a StringVar with Tkinter, I want to check that it is not empty. When I run the following condition, it is accepted while the variable is empty.

    if self.var:
        print(self.var)

The printed variable is PY_VAR1.

    if self.var!= 'PY_VAR1':
        print(self.var)

The printed variable is also PY_VAR1.

How to check that the value of self.var is not equal to PY_VAR1?

When I use get, it doesn't work either

    if self.var.get():
        print(self.var.get())

And when I change the value of self.var, with get (), nothing happens.

self.bouton = ttk.Button(self, text="print var", command=self.printvar)

def printvar(self):
      print(self.var.get())

When I click on the button, the value of self.var is displayed and even when I change the value of self.var (), the new value is displayed. But I want to display the new value of self.var without clicking on the button. I want it to display dynamically.

9
  • im not sure but try using root.update() ? Commented Jul 13, 2020 at 19:54
  • 2
    The code you posted doesn't seem to make any sense. The only place you call select_folder is from a button that isn't created until you call select_folder. Please try to create a complete minimal reproducible example - it's really hard to understand what you're asking when we only have a few lines of code. We definitely don't want your whole program, but we need more than what you've posted. If you're truly just asking how to check if a stringvar is empty, what you're doing will work. Commented Jul 13, 2020 at 20:06
  • It was just a placement error. Commented Jul 13, 2020 at 20:10
  • Why don't you just call select_folder() after you have chosen a folder inside the callback called by menu action? Commented Jul 14, 2020 at 0:34
  • I have updated my question Commented Jul 14, 2020 at 16:07

1 Answer 1

2

Try these:

# no.1
if len(string_variable.get()) == 0:
    do_task()

# no.2
'''We use try-except function so we don't get a ValueError if the specified character 
isn't present in the if-condition'''
try:
    if string_variable.index("Any character in a word that needs to be checked"):
        '''If you want to check "PY_Var1", just type('1') or any other character in 
        the if-condition.'''
        do_task()
except:
    do_task()

# If none work, try storing the StringVar in another variable.
new_string_variable = string_variable.get()
if len(new_variable_string) == 0:
    do_task()

# To check if the string variable(StringVar) isn't equal to "any_string".
if (string_variable.get()) != "any_string":
    do_task()

If you still have any problem, feel free to ask any questions!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.