我剛開始編程。我想做一個簡單的歐姆定律計算器。我正在努力檢查該條目是否為空,或者其中是否有一個或多個零。如何檢查它是否有一個或多個零?
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 (我想)。我也希望能夠用十進制數進行計算。謝謝你的幫助!
uj5u.com熱心網友回復:
如果您想檢查字串中有多少個“0”,您可以遍歷字串并使用 for 回圈將字串中的每個字母與“0”進行比較。
def check_zeros(string):
how_many_times = 0
for l in string:
if l == "0":
how_many_times = 1
return how_many_times
print(check_zeros("0Lol00xD13202130110"))
uj5u.com熱心網友回復:
在這種情況下,與其檢查一個或其他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()
uj5u.com熱心網友回復:
您可以只拆分變數:
def doMath():
U = entryU.get()
I = entryA.get()
splttedI = ''.split(I)
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")
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/361388.html
標籤:Python 特金特 tkinter-入口
