Создание GUI из простой программы преобразования температуры - PullRequest
0 голосов
/ 02 мая 2019

Мне нужно создать графический интерфейс из простой программы преобразования температуры, используя tkinter, с которой у меня нет опыта.

Программа, с которой я хотел бы сделать это, выглядит следующим образом

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

1 Ответ

1 голос
/ 02 мая 2019

Вот действительно простой код:

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) Метка (Показать вывод / результат)

enter image description here

Как это работает:

пример:

если пользователь нажимает кнопку «Преобразовать в фаренхит», функция self.convert_F является exec:

проверить значение, если число или не пусто, вычислить, отобразить результат в метке

enter image description here

enter image description here

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...