Я новичок в tkinter и пытаюсь разработать пользовательский интерфейс, в котором пользователь может выбрать свой фрукт или овощ. Мой код использует два python скрипта. Первый скрипт mainWindow.py создает окно с кнопкой и двумя пустыми метками. Нажатие кнопки «Запустить программу» вызовет скрипт «subWindow.py», который снова создаст окно с двумя кнопками. Кнопка «Выбрать фрукт и овощ» создает два списка, из которых пользователь может выбрать фрукт и овощ по своему выбору, а кнопка «Вернуть выбор в первое окно» должна вернуть выбор пользователя в первое окно, где два пустых метки будут отображать выделение.
Проблема, с которой я здесь сталкиваюсь, заключается в том, что когда я нажимаю кнопку «Вернуть выделение в первое окно» в сценарии «subwindow.py», выполнение входит в соответствующую функцию обратного вызова. и исчезает после выполнения последней строки в этой функции вместо возврата к функции 'main'. Элемент управления снова появляется, когда я снова нажимаю кнопку, и тот же цикл продолжается три раза, прежде чем элемент управления возвращается к функции «основной». Я включил свои сценарии ниже. Я искал эту проблему на inte rnet, но не смог найти решение. Любая помощь будет оценена. Заранее спасибо
# This is the mainWindow.py script
import tkinter as tk
from subWindow import subWindow
class mainWindow:
def __init__(self):
""" This function creates a GUI with a button, which will start the another window containing
two buttons """
# Create a window and obtain the screen width, screen height, window width and window height
self.mainWin = tk.Tk()
self.mainWin.title('Main Window')
scr_width = self.mainWin.winfo_screenwidth()
scr_height = self.mainWin.winfo_screenheight()
winWidth = self.mainWin.winfo_reqwidth()
winHeight = self.mainWin.winfo_reqheight()
# Position the window to the center of the screen
x_coordinate = scr_width/2 - winWidth/2
y_coordinate = scr_height/2 - winHeight/2
self.mainWin.geometry("+%d+%d" % (x_coordinate, y_coordinate))
# Pack widgets inside this window
btn1 = tk.Button(self.mainWin, text="Start the program", width=15, command=self.buttonCallback)
btn1.pack(side="top", padx=5, pady=5)
self.label1 = tk.Label(self.mainWin, text="")
self.label1.pack(side="top", padx=5, pady=5)
self.label2 = tk.Label(self.mainWin, text="")
self.label2.pack(side="top", padx=5, pady=5)
self.mainWin.mainloop()
def buttonCallback(self):
""" This function creates a new GUI from where the user can select his choice of fruit or
vegetable. Call back function for the button 'Start the program' """
sb = subWindow(self.mainWin)
[fruit, vegetable] = sb.main()
self.label1.configure(text=fruit)
self.label2.configure(text=vegetable)
if __name__ == '__main__':
m = mainWindow()
# This is the subwindow script
import tkinter as tk
class subWindow:
def __init__(self, masterWindow):
# Define the default variables
self.var1 = ""
self.var2 = 0
self.masterWindow = masterWindow
def createWidgets(self):
""" Creates and window with two buttons. The first button opens two list boxes from where the
user can select his choice of fruit and vegetable. The second button should return the user's
choices to the mainWin where they will be displayed """
# Create a tkinter window and obtain the screen and the window dimensions
self.subWin = tk.Tk()
self.subWin.grab_set()
scr_width = self.subWin.winfo_screenwidth()
scr_height = self.subWin.winfo_screenheight()
subwinWidth = self.subWin.winfo_reqwidth()
subwinHeight = self.subWin.winfo_reqheight()
# Position the window at the center of the screen
x_coordinate = scr_width/2 - subwinWidth/2
y_coordinate = scr_height/2 - subwinHeight/2
self.subWin.geometry("+%d+%d" % (x_coordinate, y_coordinate))
# Pack necessary widgets in the window
self.label1 = tk.Label(self.subWin, text='Hi there !', width=15)
self.label1.pack(side="top", padx=5, pady=5)
self.b1 = tk.Button(self.subWin, text='Select the fruit and vegetable', command=self.Callback_firstButton)
self.b1.pack(side='top', padx=5, pady=5)
self.b2 = tk.Button(self.subWin, text='Return selection to the first window', command=self.Callback_secondButton)
self.b2.pack(side='top', padx=5, pady=5)
self.subWin.mainloop()
def Callback_firstButton(self):
""" This function opens up a list box from which the user should choose a fruit and click on
OK. Callback function for the button 'Select the fruit and vegetable """
# Create a tkinter window and obtain the screen and the window dimensions
self.win1 = tk.Tk()
scr_width = self.win1.winfo_screenwidth()
scr_height = self.win1.winfo_screenheight()
winWidth = self.win1.winfo_reqwidth()
winHeight = self.win1.winfo_reqheight()
# Position the window to the center of the screen
x_coordinate = scr_width / 2 - winWidth / 2
y_coordinate = scr_height / 2 - winHeight / 2
self.win1.geometry("+%d+%d" % (x_coordinate, y_coordinate))
# Pack necessary widgets in the window
self.label2 = tk.Label(self.win1, text="Choose a fruit")
self.label2.pack(side='top', fill='x', expand=True, padx=5, pady=5)
self.lb1_values = ['apples', 'oranges', 'mangoes']
self.lb1 = tk.Listbox(self.win1, selectmode=tk.SINGLE)
self.lb1.pack(side='top', fill='x', expand=True)
for item in self.lb1_values:
self.lb1.insert(tk.END, item)
self.b3 = tk.Button(self.win1, text="OK", command=self.FirstListBoxSelection)
self.b3.pack(side='top', fill='x', expand=True, padx=5, pady=5)
self.win1.mainloop()
def FirstListBoxSelection(self):
""" This function extracts the selection of the user from the first list box and creates
another list box, from which the user should select a vegetable. Call back function for the
OK button on the first listbox """
# Get the selection from the previous listbox window
self.index1 = self.lb1.curselection()[0]
self.var1 = self.lb1_values[self.index1]
self.win1.destroy()
# Create a tkinter window and obtain the screen and the window dimensions
self.win2 = tk.Tk()
scr_width = self.win2.winfo_screenwidth()
scr_height = self.win2.winfo_screenheight()
winWidth = self.win2.winfo_reqwidth()
winHeight = self.win2.winfo_reqheight()
# Position the window to the center of the screen
x_coordinate = scr_width / 2 - winWidth / 2
y_coordinate = scr_height / 2 - winHeight / 2
self.win2.geometry("+%d+%d" % (x_coordinate, y_coordinate))
self.label3 = tk.Label(self.win2, text="Choose a vegetable")
self.label3.pack(side='top', fill='x', expand=True, padx=5, pady=5)
self.lb2_values = ['carrot', 'potato', 'beans']
self.lb2 = tk.Listbox(self.win2, selectmode=tk.SINGLE)
self.lb2.pack(side='top', fill='x', expand=True)
for item in self.lb2_values:
self.lb2.insert(tk.END, item)
self.b4 = tk.Button(self.win2, text="OK", command=self.SecondListBoxSelection)
self.b4.pack(side='top', fill='x', expand=True, padx=5, pady=5)
self.win2.mainloop()
def SecondListBoxSelection(self):
""" This function returns the user's selection of vegetable from the second list box.
Callback function for the OK button on the second listbox """
# Get the selection from the previous listbox window
self.index2 = self.lb2.curselection()[0]
self.var2 = self.lb2_values[self.index2]
self.win2.destroy()
def Callback_secondButton(self):
""" This function should quit the subWindow and give control back to the main function """
# PROBLEM: This function needs to be executed thrice in order for the control to return back
to the main function
self.subWin.quit()
def main(self):
""" This is the main function which should return both user's selection to the mainWin
created """
self.createWidgets()
return self.var1, self.var2