저는 Python을 처음 접했고 단위를 변환하는 프로그램 (tkinter 사용)을 만들려고합니다. 5 번째 줄에 문제가있는 것 같아요. 누구든지 내 코드를 검토하고 수정하도록 제안 할 수 있습니까? 감사합니다
choices = {'feet': 0.3048, 'inches': 0.0254}
choice = StringVar()
popupChoice = OptionMenu(secondFrame, choice, *choices)
popupChoice.pack()
pick_choice = choices[choice.get()]
def calculate(*args):
try:
value = float(feet.get())
meter.set(value*float(pick_choice))
except ValueError:
print("error")
StringVar ()는 기본적으로 빈 문자열 ''을 제공하므로 사전에 아무것도 도달 할 수 없으며 KeyError가 발생합니다. 간단합니다.
# choices.keys() will provide list of your keys in dictionary
if choice.get() in choices.keys():
pick_choice = choices[choice.get()]
또는 그 전에 기본값을 설정할 수 있습니다. 예를 들면 다음과 같습니다.
choice = StringVar()
choice.set("feet")
예, 어떻게 보일 수 있는지 :
from tkinter import *
def calculate():
try:
value = float(feet.get())
label.config(text=str(value*float(choices[choice.get()])))
except ValueError or KeyError:
label.config(text='wrong/missing input')
# config can change text and other in widgets
secondFrame = Tk()
# entry for value
feet = StringVar()
e = Entry(secondFrame, textvariable=feet)
e.grid(row=0, column=0, padx=5) # grid is more useful for more customization
# label showing result or other text
label = Label(secondFrame, text=0)
label.grid(row=0, column=2)
# option menu
choices = {'feet': 0.3048, 'inches': 0.0254}
choice = StringVar()
choice.set("feet") # default value, to use value: choice.get()
popupChoice = OptionMenu(secondFrame, choice, *choices)
popupChoice.grid(row=0, column=1, padx=5)
# button to launch conversion, calculate is not called with variables
# call them in function, or use lambda function - command=lambda: calculate(...)
button1 = Button(secondFrame, command=calculate, text='convert')
button1.grid(row=1, column=1)
secondFrame.mainloop()
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다