python - Tkinter 检查 StringVar 是否不为空

标签 python tkinter

我有一个带 Tkinter 的 StringVar,我想检查它是否不为空。当我运行以下条件时,它在变量为空时被接受。

    if self.var:
        print(self.var)

打印出来的变量是PY_VAR1。

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

打印出来的变量也是PY_VAR1。

如何判断self.var的值不等于PY_VAR1?

我用get的时候也是不行

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

当我使用 get () 更改 self.var 的值时,没有任何反应。

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

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

当我点击按钮时,会显示 self.var 的值,甚至当我更改 self.var() 的值时,也会显示新值。但是我想在不单击按钮的情况下显示 self.var 的新值。我希望它动态显示。

最佳答案

试试这些:

# 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()

如果您还有任何问题,请随时提出任何问题!

关于python - Tkinter 检查 StringVar 是否不为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62883216/

相关文章:

python - 如何使用全局参数跳过 python unittest

python - 如何让 tkinter 窗口在 LINUX 中显示

python - 如何根据Python中另一个 tkinter `Scale` 小部件的值来控制 tkinter `Scale` 小部件的值?

未定义 Python 多处理池函数

python - psycopg2 共享内存不足并提示增加 max_pred_locks_per_transaction

javascript - 使用 Flask 时出错 Angular.js

python - ViterbiParser 和 ChartParser 在 NLTK 中为 PCFG 返回 None

python - TypeError: printName1() 采用 0 个位置参数,但给出了 1 个

python - `tkinter.iconbitmap` 方法返回空字符串

python - 使用颜色列表中的 for 循环更改 Tkinter 框架颜色