import tkinter as tk class App: def init(self, master=None): if master is None: master = tk.Tk() master.title("My App") master.geometry("400x300") self.master = master else: self.master = master self.master.title("My App") self.master.geometry("400x300") self.menu_bar = tk.Menu(self.master, tearoff=0) self.menu_bar.pack() self.create_menu() def create_menu(self): self.menu_bar.delete(1, tk.END) self.menu_bar.insert(tk.END, "Option") self.menu_bar.insert(tk.END, "Option") self..insert(tk.END, "Option") root = tk.Tk() app = App(root) root.mainloop(),这段代码报错self.tk.call( _tkinter.TclError: can't pack ".!menu": it's a top-level window,如何解决?
时间: 2024-03-01 07:51:09 浏览: 131
根据代码,您在 create_menu() 方法中有一行代码 `self..insert(tk.END, "Option")`,其中有一个多余的点号。您需要将该行代码修改为 `self.menu_bar.insert(tk.END, "Option")`,即可解决该报错。这是因为在原代码中多打了一个点号,导致程序无法正确识别该菜单栏选项所属的控件,从而报错。修改后的代码如下:
```
import tkinter as tk
class App:
def __init__(self, master=None):
if master is None:
master = tk.Tk()
master.title("My App")
master.geometry("400x300")
self.master = master
else:
self.master = master
self.master.title("My App")
self.master.geometry("400x300")
self.menu_bar = tk.Menu(self.master, tearoff=0)
self.menu_bar.pack()
self.create_menu()
def create_menu(self):
self.menu_bar.delete(1, tk.END)
self.menu_bar.insert(tk.END, "Option")
self.menu_bar.insert(tk.END, "Option")
self.menu_bar.insert(tk.END, "Option")
root = tk.Tk()
app = App(root)
root.mainloop()
```
请注意,如果报错信息中仍然提示顶级窗口无法进行 pack() 操作,请检查代码中是否存在其他对顶级窗口进行布局操作的错误。
阅读全文