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 10:52:02 浏览: 65
Python(十)- tkinter案例(1): WiFi连接器
这个错误是因为你使用了 `self.insert` 而不是 `self.menu_bar.insert`,导致在菜单栏中插入了一个顶级窗口,而菜单栏只能包含菜单项目。你可以将 `self.insert` 改为 `self.menu_bar.insert`。修改后的代码如下:
```
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
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")
root = tk.Tk()
app = App(root)
root.mainloop()
```
这样就不会出现这个错误了。
阅读全文