简体   繁体   English

Python 3.3 GUI程序

[英]Python 3.3 GUI Program

Celsius to Fahrenheit-- Write a GUI program that converts Celsius temperatures to Fahrenheit temperatures. 摄氏到华氏温度-编写一个将摄氏温度转换成华氏温度的GUI程序。 The user should be able to enter a Celsius temperature, click a button, and then see the equivalent Fahrenheit temperature. 用户应该能够输入摄氏度温度,单击按钮,然后查看等效的华氏温度。 Use the following formula to make the conversion: F = 9/5C +32 F is the Fahrenheit temperature and C is the Celsius temperature. 使用以下公式进行转换:F = 9 / 5C +32 F是华氏温度,C是摄氏温度。

THIS IS THE CODE I HAVE SO FAR, THE ERROR I GET says "invalid literal for int() with base 10: ''" I need help getting it to run correctly. 这是我非常了解的代码,我得到的错误是“对于以10为底的int()无效的文字:”,我需要帮助以使其正确运行。

#import
#main function
from tkinter import *
def main():
    root=Tk()

    root.title("Some GUI")
    root.geometry("400x700")
    #someothersting=""
    someotherstring=""
#enter Celcius
    L1=Label(root,text="Enter a Celcius temperature.")
    E1=Entry(root,textvariable=someotherstring)
    somebutton=Button(root, text="Total", command=convert(someotherstring))

    somebutton.pack()
    E1.pack()
    L1.pack()
    root.mainloop()#main loop


#convert Celcius to Fahrenheit
def convert(somestring):
    thestring=""
    thestring=somestring
    cel=0
    far=0
    cel=int(thestring)
    far=(9/5*(cel))+32
    print(far)

Your main problem is this line; 您的主要问题是这条线;

somebutton=Button(root, text="Total", command=convert(someotherstring))

...which will call convert(someotherstring) immediately and assign the result to command. ...这将立即调用convert(someotherstring)并将结果分配给命令。 Since someotherstring is empty when this line is reached, it will fail to convert the value and fail the program. 由于到达该行时someotherstring为空,因此它将无法转换值并使程序失败。

If you don't want it evaluated immediately but instead on button press, you can use a lambda as a command; 如果您不希望立即评估它,而只需按一下按钮,就可以使用lambda作为命令。

somebutton=Button(root, text="Total", command=lambda: convert(E1.get()))

...which will eliminate the use of someotherstring completely and just call convert with the contents of E1 when the button is clicked. ...这将完全someotherstring使用其他someotherstring ,只需在单击按钮时使用E1的内容调用convert。

This could be due to int("") 这可能是由于int("")

In main(), do 在main()中,执行

def main():
    # ...
    someotherstring = 0 # Since its trying to get int

Or you can check if its empty in convert() : 或者您可以在convert()检查其是否为空:

def convert(somestring):
    if somestring != "":    
        # cel=0 dont need these in python
        # far=0
        cel=int(somestring)
        far=(9/5*(cel))+32
        print(far)

Note: Check if you are using someotherstring properly with Entry widget. 注意:检查Entry小部件是否正确使用了其他someotherstring I believe you are supposed to use StringVar() and do stringvar.get() to get the text inside widget. 我相信您应该使用StringVar()并执行stringvar.get()来获取小部件内的文本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM