我有一个tkinter
应用程序,我已经在课程中创建了它。
第一个是class MainWindow()
,主窗口正在绘制。
另一个是class SettingsWindow()
,其中选项窗口正在绘制。
我将在class2中使用class1中的on_exit
方法。如何正确地解决它?
还有一件事,如何正确创建SettingsWindow
?我在下面抛出错误的方式,这表明我错过了争论。
mainWindow = MainWindow() TypeError: init ()缺少1个必需的位置参数:' master'
代码:
class MainWindow():
def __init__(self, master):
self.master = master
...
some widgets
...
# Trying to create SettingsWindow object
def open_settings(self):
settingsWindowsToplevel = Toplevel()
settingsWindow = SettingsWindow(self, MainWindow)
# The function i'm gonna use in another class
def on_exit(self):
self.master.exit_button()
class SettingsWindow():
def __init__(self, parent, master):
self.master = master
...
some widgets again
...
# Creating main window
def main():
root = Tk()
mainWindow = MainWindow(root)
root.mainloop()
if __name__ == "__main__":
main()
我需要从其他课程启动许多功能,而我无法通过tkinter
了解如何正确地执行此操作。
感谢。
答案 0 :(得分:0)
这不是您正在寻找的解决方案,但我认为考虑好。一切都在一个Tk类中实现,在这种情况下总是只有一个窗口。但是如果有人知道的话,我也希望看到继承的解决方案。
from tkinter import *
from tkinter import ttk
class MainWindow():
def __init__(self, mainWidget):
self.main_frame = ttk.Frame(mainWidget, width=300, height=150, padding=(0, 0, 0, 0))
self.main_frame.grid(row=0, column=0)
self.some_kind_of_controler = 0
self.main_gui()
def main_gui(self):
root.title('My Window')
self.main_label_1 = ttk.Label(self.main_frame, text='Object_1')
self.main_label_1.grid(row=0, column=0)
self.main_label_2 = ttk.Label(self.main_frame, text='Object_2')
self.main_label_2.grid(row=1, column=0)
self.main_label_3 = ttk.Label(self.main_frame, text='Object_3')
self.main_label_3.grid(row=2, column=0)
self.setings_button = ttk.Button(self.main_frame, text='Setings')
self.setings_button.grid(row=0, column=1)
self.setings_button.bind('<Button-1>', self.setings_gui)
self.gui_elements = [self.main_label_1,
self.main_label_2,
self.main_label_3,
self.setings_button]
def setings_gui(self, event):
self.gui_elements_remove(self.gui_elements)
root.title('Setings')
self.main_label_1 = ttk.Label(self.main_frame, text='Object_1')
self.main_label_1.grid(row=2, column=0)
self.main_menu_button = ttk.Button(self.main_frame, text='Main menu')
self.main_menu_button.grid(row=0, column=1)
self.main_menu_button.bind('<Button-1>', self.back_to_main)
self.some_kind_of_controler = 1
self.gui_elements = [self.main_label_1,
self.main_menu_button]
def back_to_main(self, event):
if self.some_kind_of_controler == 1:
self.gui_elements_remove(self.gui_elements)
else:
pass
self.main_gui()
def gui_elements_remove(self, elements):
for element in elements:
element.destroy()
def main():
global root
root = Tk()
root.geometry('300x150+50+50')
window = MainWindow(root)
root.mainloop()
if __name__ == '__main__':
main()
答案 1 :(得分:0)
通常的做法是将主窗口的引用传递给设置窗口:
class SettingsWindow():
def __init__(self, parent, master):
self.master = master
...
def on_exit(self):
self.master.exit_button()
mainWindow = MainWindow(...)
...
settingsWindow = SettingsWindow(..., mainWindow)