【问题标题】:Python 3.3 GUI ProgramPython 3.3 图形用户界面程序
【发布时间】:2013-12-05 19:11:55
【问题描述】:

摄氏到华氏——编写一个 GUI 程序,将摄氏温度转换为华氏温度。用户应该能够输入摄氏温度,单击按钮,然后看到等效的华氏温度。使用以下公式进行转换: F = 9/5C +32 F 是华氏温度,C 是摄氏温度。

这是我到目前为止的代码,我得到的错误是“invalid literal for int() with base 10: ''”我需要帮助才能让它正确运行。

#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)

【问题讨论】:

  • 您在someotherstring 的字段中输入了什么,听起来您输入了“10C”或int() 无法解析的内容。

标签: python user-interface tkinter python-3.3


【解决方案1】:

你的主要问题是这条线;

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

...它将立即调用convert(someotherstring) 并将结果分配给命令。由于到达此行时 someotherstring 为空,因此将无法转换值并导致程序失败。

如果您不想立即评估它,而是在按下按钮时进行评估,您可以使用 lambda 作为命令;

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

...这将完全消除someotherstring 的使用,只需在单击按钮时使用E1 的内容调用convert。

【讨论】:

    【解决方案2】:

    这可能是由于int("")

    在main()中,做

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

    或者您可以在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)
    

    注意:检查您是否正确使用 someotherstring 和 Entry 小部件。我相信您应该使用StringVar() 并使用stringvar.get() 来获取小部件内的文本。

    【讨论】:

    • 这只是问题的一部分。问题的另一部分是转换如何绑定到按钮。
    • @BryanOakley 同意。我完全错过了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-18
    相关资源
    最近更新 更多