我有一些测试代码,它定义了几个窗口和函数(一个用于显示框架,一个用于新窗口)。我有一个创建new_window函数的错误,因为它不会打开指定的窗口,而是打开一个空白的窗口。我认为这是因为我已经在类中定义了与主类相关的窗口,并且框架是在其中定义的,但是窗口不是,但我担心我对如何调试感到很遗憾。
任何帮助非常感谢!
import tkinter as tk
from tkinter import ttk
from tkinter.filedialog import askopenfilename
class Randomize(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.wm_title(self, "Randomize those names!")
container = tk.Frame(self)
container.pack(side="top", fill="both", expand = True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (HomeWindow, NewWin):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(HomeWindow)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
##trying to create a new window instead of just changing the original one
def new_window(self, cont):
window = tk.Toplevel(self)
window.tkraise()
class HomeWindow(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
label = ttk.Label(self, text="Choose a File and Start")
label.pack(pady=10,padx=10)
##calls NewWin in a new frame but the same window, works
button = ttk.Button(self, text="File",
command=lambda: controller.show_frame(NewWin))
button.pack()
##should call NewWin through new_window, instead opens blank window
button2 = ttk.Button(self, text="New Window",
command=lambda: controller.new_window(NewWin))
button2.pack()
class NewWin(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = ttk.Label(self, text="NewWindow")
label.pack(pady=10,padx=10)
button1 = ttk.Button(self, text="Back to Home",
command=lambda: controller.show_frame(HomeWindow))
button1.pack()
app = Randomize()
app.mainloop()
答案 0 :(得分:0)
应该是
def new_window(self, cont):
window = tk.Toplevel(self)
frame = cont(window, window) # cont = NewWin
frame.pack()
但框架中的按钮不起作用。新窗口没有show_frame()
方法。
也许你使用
frame = cont(window, self) # self
然后在新窗口中的按钮将改变主窗口中的帧。