如果条件和清除条目在 tkinter 中如何工作?

How if condition and clear the entry works in tkinter?

def Input(PIn , BIn , AIn) :
    if (PIn ==0) and (BIn ==0) and (AIn == 0)  :
         print ("ok")

    else :
         str(PIn)
         int(BIn)
         int(AIn)
         global n
         proc.append([PIn , BIn , AIn ])
         n+=1
         PIn.delete(0,END)
         BIn.delete(0,END)
         AIn.delete(0,END)
         print(proc , n)

我正在尝试将我的 python 代码转换为 GUI,但我遇到了两个问题。第一个是 if 语句不起作用,因此如果用户为所有变量输入 0,它将转到 else。第二个是我无法清除条目。

在您的第一期中,通常 TKinter 条目小部件会将值作为字符串传递。很难肯定地说,因为您没有提供 PIn、BIn、AIn 变量的示例代码,但很可能您正在将字符串与整数进行比较,这将评估为 false。

尝试将 if 语句替换为 if (PIn == "0") and (BIn == "0") and (AIn == "0"):(将字符串与字符串进行比较)或 if (int(PIn) == 0) and (intBIn) == 0) and (int(AIn) == 0):(将整数与整数进行比较)。

关于你的第二点,我认为你需要提供更多关于 PIn、BIn 和 AIn 是什么类型的小部件的详细信息。

如果你想从 tkinter 的条目小部件中编辑/获取值,你需要使用

tkinter.StringVar()


PIn_text_var = StringVar() 
PIn = Entry(root, textvariable=PIn_text_var)

#To edit the widget's text : 

PIn_text_var.set("new value") 

#To get the widgets text :

s = PIn_text_var.get()
print(s) 
# output : 'new value'

如果您想清除条目小部件的 文字:

PIn_text_var.set("") 

至于你的例子:


PIn_text_var = tkinter.StringVar() 
BIn_text_var = tkinter.StringVar() 
AIn_text_var = tkinter.StringVar()

proc = []
n = 0 

def Input () :
    global n

    P = PIn_text_var.get()
    B = BIn_text_var.get()
    A = AIn_text_var.get() 

    if (P=="0") and (B=="0") and (A=="0") : 
        print ("ok") 

    else : 
        temp_var_p = P
        temp_var_b = int(B)
        temp_var_a = int(A)

        proc.append([temp_var_p, temp_var_b, temp_var_a ]) 

        PIn_text_var.set("")
        BIn_text_var.set("")
        AIn_text_var.set("")
        n+=1
        print(proc , n)

问题是您正在将小部件本身与一个值进行比较。小部件与值不同。您必须先从小部件获取值,然后才能将它与任何东西进行比较。

由于条目的 get 方法将 return 一个字符串,我建议与字符串进行比较。另一种选择是在比较之前将值转换为整数,但在这种情况下,您必须准备好处理用户输入无法转换为整数的内容的情况。

if (PIn.get() == "0") and (BIn.get() == "0") and (AIn.get() == "0") ...