如何检查 tkinter 中的条目是否有一个或多个零

How can I check if an entry in tkinter has one or more zeros

我刚开始编程。我想做一个简单的欧姆定律计算器。我正在努力检查条目是否为空,或者其中是否有一个或多个零。我如何检查它是否有一个或多个零?

from tkinter import *
import math as m

def doMath():
   U = entryU.get()
   I = entryA.get()
   if I == "0" or \
      I == "" or \
      U == "":                                                        
      labelR.config(text="Error", bg= "red")   
   else:                                              
      R = float(U)/float(I)                                       
      labelR.config(text="Resistance: {:.2f}\u03A9".format(R), bg="white")

frame = Tk()
entryU = Entry(frame)
entryU.place (x=95, y= 60, width= 250, height =30)

entryA= Entry(frame)
entryA.place(x=95, y=100, width= 250, height=30)

buttonMath = Button(frame, text="R",command = doMath)
buttonMath.place(x=360, y=70, width=120, height=50)

labelR = Label (frame, text="Resistance: ")
labelR.place(x=10, y= 145) 

frame.mainloop()

这就是我所拥有的,但是一旦我的字符串中有“00”,这显然就不会起作用,如果我尝试只检查 I==0 它就不会起作用,因为我无法比较带有 int 的字符串(我想)。我也希望能够用十进制数进行计算。 感谢您的帮助!

如果你想检查字符串中有多少个“0”,你可以使用 return string.count("0") 感谢@martineau 对我的教育 :)

def check_zeros(string):
    return string.count("0")

print(check_zeros("0Lol00xD13202130110"))

抱歉,你应该把它列成一个列表,这样你就可以数一数里面有多少个 0:

def doMath():
    U = entryU.get()
    I = entryA.get()
    splttedI = []
    for x in I:
       if x == 0:
            splyttedI.append(x)
    howmanytimes = len(splttedI)
    if "0" in splttedI or \
       I == "" or \
       U == "":                                                        
       labelR.config(text="Error", bg= "red")   
    else:                                              
        R = float(U)/float(I)                                              
        labelR.config(text="Resistance: {:.2f}\u03A9".format(R), bg="white")

在这种情况下,与其检查一个或另一个 Entry 小部件中的特定错误,不如只处理其中一个无法转换为 float 出于任何原因 — 因为这才是真正重要的。

如果在尝试进行转换时发生错误,那么您可以尝试诊断问题并可能弹出一个消息框或带有其他错误信息的东西。但是,如果您考虑一下,输入无效内容的方法有很多,所以我不确定是否值得麻烦。

请注意,在 成功转换后,您可能仍想检查潜在的价值问题 ,例如 I 成为 0

无论如何,这里是实现我最初建议的简单方法的方法:

from tkinter import *
import math as m

def doMath():
    U = entryU.get()
    I = entryA.get()
    try:
        R = float(U) / float(I)
    except ValueError:
        labelR.config(text="Error", bg= "red")
        return
    labelR.config(text="Resistance: {:.2f}\u03A9".format(R), bg="white")


frame = Tk()
frame.geometry('500x200')
entryU = Entry(frame)
entryU.place(x=95, y=60, width=250, height=30)

entryA = Entry(frame)
entryA.place(x=95, y=100, width= 250, height=30)

buttonMath = Button(frame, text="R", command=doMath)
buttonMath.place(x=360, y=70, width=120, height=50)

labelR = Label(frame, text="Resistance: ")
labelR.place(x=10, y= 145)

frame.mainloop()