我需要使用tkinter从一个简单的温度转换程序创建一个GUI,我没有经验。
我要使用的程序如下
temp=float(input("Enter a temperature value to convert: "))
unit=str(input("Convert to Fahrenheit or Celsius? Enter f or c: "))
if unit=="c" or unit == "C":
degC=(temp)
temp=(1.8*temp)+32
print (str(round(temp,1)) + " degrees fahrenheit = " + str(degC) + " degrees Celsius. ")
elif unit=="f" or unit == "F":
degF=(temp)
temp=(temp-32)/1.8
print (str(round(temp,1))+ " degrees celsius = " + str(degF) + " degrees Fahrenheit. ")
else:
print("you did not enter an f or c. Goodbye ")
答案 0 :(得分:1)
这是一个非常基本的代码:
from Tkinter import *
import Tkinter as tk
import ttk
import tkMessageBox
class Temperature:
def __init__(self, dlg) :
self.dlg = dlg
self.dlg.title ('MyApp-calculate temperature')
# Define widgets
ttk.Label(self.dlg, text="Enter a temperature value to convert:").grid (row = 0, column = 0)
self.n = ttk.Entry(self.dlg)
self.n.grid (row = 0, column = 1)
ttk.Button(self.dlg, text="Convert to Fahrenheit", command=self.convert_F).grid(row=1, column=0)
ttk.Button(self.dlg, text="Convert to Celsius", command=self.convert_C).grid(row=1, column=1)
self.label = ttk.Label(self.dlg, text=" ")
self.label.grid(row=2, column=0)
def convert_F(self):
if self.n.get().isdigit() and self.n.get() != '': #Check if number and its not empty
temp = float(self.n.get())
degF = (temp)
temp = (temp - 32) / 1.8
self.label['text'] = (str(round(temp, 1)) + " degrees celsius = " + str(degF) + " degrees Fahrenheit. ")
else:
self.label['text'] = "you did not enter an f or c. Goodbye "
def convert_C(self):
if self.n.get().isdigit() and self.n.get() != '': # Check if number and its not empty
temp = float(self.n.get())
degC = (temp)
temp = (1.8 * temp) + 32
self.label['text'] = (str(round(temp, 1)) + " degrees fahrenheit = " + str(degC) + " degrees Celsius. ")
else:
self.label['text'] = "you did not enter an f or c. Goodbye "
if __name__ == '__main__':
dlg = Tk()
application = Temperature(dlg)
dlg.mainloop()
具有5个小部件的简单对话框:
1)标签(输入要转换的温度值)
2)条目(用户输入)
3)按钮(转换为华氏度)
4)按钮(转换为摄氏度)
5)标签(显示输出/结果)
其工作方式:
示例:
如果用户单击按钮“转换为Farenhit”功能self.convert_F为exec:
检查数值是否为空,计算并在“标签”中显示结果