В настоящее время у меня возникла проблема с работой некоторых частей моего приложения. Я хочу добавить радиокнопки и кнопку преобразования, чтобы пользователи могли конвертировать из Фаренгейта в Цельсий и наоборот. При добавлении определенных функций и переменных во второе окно параметры кажутся серыми и препятствуют правильному выполнению кода.
Я пробовал постепенно добавлять определенные определения и функции, и это сработало, но мне все еще трудно привести их в нужный формат. Я использовал глобальную переменную, чтобы гарантировать, что я общаюсь только со вторым окном, но, похоже, не обрабатываю определенные функции.
def openNewWindow():
global NewWindow
#Creates a new window using Toplevel
NewWindow = Toplevel(master_window)
#Sets the title of Toplevel widget
NewWindow.title("Dave's weather app")
#Sets the geometry of Toplevel
NewWindow.geometry('350x350')
#Label widget to show in Toplevel
Label(NewWindow, text = "Temperature Conversion", fg = 'gold', bg = 'dark blue', font = ('bold, 12')).pack()
#Configures window color
NewWindow.configure(bg = 'dark blue')
#Temperature input block that allows the user to input a number within the program
label = Label(NewWindow, text = "Enter Temperature:").pack()
entry = Entry(NewWindow).pack()
#Convert button acts as an enter key and allows the program to process the number
convert_btn = Button(NewWindow, text = "Convert", command = convert_temperature).pack()
#Result label outputs
result_label = Label(NewWindow, text = "").pack()
#Defines the formula to convert Celsius to Fahrenheit
def Celsius_to_Fahrenheit(Celsius):
return (1.8) * Celsius + 32
#Defines the formula to convert Fahrenheit to Celsius
def Fahrenheit_to_Celsius(Fahrenheit):
return (0.55) * (Fahrenheit - 32)
#Main NewWindow welcome screen
master_window = Tk()
master_window.title("Welcome Screen")
master_window.configure(bg = 'dark blue')
master_window.geometry('200x200')
#Welcome label for the master window
label = Label(master_window, text = "Welcome!")
label.pack( pady = 10)
#Button to open Dave's weather app
btn1 = Button(master_window, text = "Click to open Dave's Weather app", command = openNewWindow)
btn1.pack(expand = True)
#Welcome screen exit button
btn2 = Button(master_window, text = "Exit", command = exit)
btn2.pack(expand = True)
mainloop()
Вы также можете ознакомиться с PEP8 — следование руководству по стилю Python поможет вам написать лучший Python, который вам будет легче отлаживать, а другим будет легче читать. Вам также следует избегать импорта звездочек, а также объявления и упаковки виджетов в одной строке, например convert_btn = Button(...).pack()
, потому что pack
возвращает None
, что означает, что convert_btn
есть None
И, кстати, global NewWindow
вам не нужен - здесь он ничего не делает.
@Reesecup, пожалуйста, посмотри мой ответ. Мой код работает так, как вы ожидали
Это полный код. Радиокнопки должны быть объявлены, как показано в коде. Чтобы получить значение переключателя, объявляется строковая переменная с именем tempvar. tempvar = StringVar()
. Используя tempvar.get()
, мы можем получить значение. Строковая переменная должна быть сопоставлена с помощью радиокнопок с помощью variable = tempvar
. Аналогично, значение записи определяется entry.get()
. Вместо объявления глобальных переменных я разместил функцию convert_temperature()
внутри окна верхнего уровня. Результат отображается с помощью label.configure
. Обратите внимание: если виджеты объявлены как переменные с именем переменной, их нельзя упаковать напрямую. Его можно упаковать только в следующей строке, используя widget_name.pack()
from tkinter import *
def openNewWindow():
def convert_temperature():
temp = entry.get()
temp = int(float(temp))
type = tempvar.get()
if type == 'celc':
result = (1.8) * temp + 32
else: result = (0.55) * (temp - 32)
result_label.configure(text = result)
#Creates a new window using Toplevel
NewWindow = Toplevel(master_window)
#Sets the title of Toplevel widget
NewWindow.title("Dave's weather app")
#Sets the geometry of Toplevel
NewWindow.geometry('350x350')
#Label widget to show in Toplevel
Label(NewWindow, text = "Temperature Conversion", fg = 'gold', bg = 'dark blue', font = ('bold, 12')).pack()
#Configures window color
NewWindow.configure(bg = 'dark blue')
tempvar = StringVar()
celc = Radiobutton(NewWindow, variable = tempvar, value = 'celc', text = 'Convert from Celsius to Fahrenheit')
celc.pack()
fheit = Radiobutton(NewWindow, variable = tempvar, value = 'fheit', text = 'Convert from Fahrenheit to Celsius')
fheit.pack()
#Please Note when widget is assigned to a variable name, declare variable separately and pack the variable in next line
label = Label(NewWindow, text = "Enter Temperature:")
label.pack()
entry = Entry(NewWindow)
entry.pack()
#Convert button acts as an enter key and allows the program to process the number
convert_btn = Button(NewWindow, text = "Convert", command = convert_temperature)
convert_btn.pack()
#Result label outputs
result_label = Label(NewWindow, text = "")
result_label.pack()
#Main NewWindow welcome screen
master_window = Tk()
master_window.title("Welcome Screen")
master_window.configure(bg = 'dark blue')
master_window.geometry('200x200')
#Welcome label for the master window
label = Label(master_window, text = "Welcome!")
label.pack( pady = 10)
#Button to open Dave's weather app
btn1 = Button(master_window, text = "Click to open Dave's Weather app", command = openNewWindow)
btn1.pack(expand = True)
#Welcome screen exit button
btn2 = Button(master_window, text = "Exit", command = exit)
btn2.pack(expand = True)
master_window.mainloop()
Здесь не определена функция
convert_temperature
, поэтому вы сталкиваетесь с исключениемNameError
вopenNewWindow
, из-за которого элементы, расположенные ниже по потоку, не отображаются в графическом интерфейсе. В частности, эта строка попадает в исключение:convert_btn = Button(NewWindow, text = "Convert", command = convert_temperature).pack()