我的功能不起作用,我正在嘗試構建一個帶有 GUI 的簡單程式。它可以通過從用戶那里獲取一些溫度和鍵來將任何溫度從任何標度轉換為開爾文標度,以告知您輸入的溫度標度的功能,這是您可以使用的鍵 C or c == Celsius, K or k == kelvin, F or f == Fahrenheit and return [the key is unavailable] if the isn't one of them。但是當我輸入這些鍵中的任何鍵時,它回傳的值與我給它的值相同。
這是我的代碼:
from tkinter import *
from tkinter import ttk
from turtle import width, window_width
from Science import Kelvin
window = Tk()
window.title('Chemical Physics')
window.geometry("300x200 10 20")
GetButton = ttk.Button(window, text = "--> Click here <--")
GetButton.pack()
EntryKelvinNumber = ttk.Entry(window, width = 40)
EntryKelvinNumber.pack()
EntryKelvinKey = ttk.Entry(window, width = 20)
EntryKelvinKey.pack()
def GetKelvinButton():
# the Kelvin function just return the same value
print(Kelvin(EntryKelvinNumber.get(),EntryKelvinKey.get()))
GetButton.config(command = GetKelvinButton)
window.mainloop()
這一行from Science import Kelvin是從我自己的庫中匯入開爾文函式。
這是一個開爾文函式代碼:
def helpS():
print("pleas use:\n")
print("use 0 if your temperature is Kelvin\n")
print("use 1 if your temperature is Celsius\n")
print("use 2 if your temperature is Fahrenheit\n")
#soon...
def Kelvin(Tempereture,key):
if key == 'K' or 'k':
return Tempereture
elif key == 'C' or 'c':
return Tempereture 273.15
elif key == 'F' or 'f':
i = (Tempereture - 32)/1.8
i = i 273.15
return i
else:
print("the key is unavailable")
helpS()
我試圖使鍵成為數字0 == Kelvin, 1 == Celsius, and 2 == Fahrenheit,但它仍然不起作用。
uj5u.com熱心網友回復:
if key == 'K' or 'k':
相當于
if (key == 'K') or ('k'):
這相當于
if True:
因為bool('k')是True。
你可能想寫
if key == 'K' or key == 'K':
另外,確保溫度變數是函式中的一個數字,Kelvin因為EntryKelvinNumber.get()它將回傳一個字串。
def Kelvin(Tempereture, key):
Tempereture = float(Tempereture)
# rest of Kelvin function
uj5u.com熱心網友回復:
這只是 Python 語法的問題,您將不得不使用下面的代碼。如果您正在制定該條件,則必須在“或”之后使用相同的條件陳述句,只是使用不同的值。
def Kelvin(Tempereture,key):
if key == 'K' or key == 'k':
return Tempereture
elif key == 'C' or key == 'c':
return Tempereture 273.15
elif key == 'F' or key == 'f':
i = (Tempereture - 32)/1.8
i = i 273.15
return I
else:
print("the key is unavailable")
helpS()
print(Kelvin(50, "c"))
希望這有效。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/511698.html
