python寫一個多級菜單欄中多級子菜單的gui窗口,每個子菜單在窗口顯示的内容和標簽和文本框都不一樣
时间: 2023-11-27 15:54:07 浏览: 53
以下是一个基于Tkinter的Python多级菜单栏中多级子菜单的GUI窗口的示例代码:
```python
import tkinter as tk
class MenuBar:
def __init__(self, master):
self.master = master
self.menu_bar = tk.Menu(self.master)
self.sub_menu1 = tk.Menu(self.menu_bar, tearoff=0)
self.sub_menu2 = tk.Menu(self.menu_bar, tearoff=0)
self.sub_menu3 = tk.Menu(self.menu_bar, tearoff=0)
self.menu_bar.add_cascade(label="File", menu=self.sub_menu1)
self.menu_bar.add_cascade(label="Edit", menu=self.sub_menu2)
self.menu_bar.add_cascade(label="Help", menu=self.sub_menu3)
self.sub_menu1.add_command(label="New", command=self.new_file)
self.sub_menu1.add_command(label="Open", command=self.open_file)
self.sub_menu1.add_command(label="Save", command=self.save_file)
self.sub_menu2.add_command(label="Cut", command=self.cut_text)
self.sub_menu2.add_command(label="Copy", command=self.copy_text)
self.sub_menu2.add_command(label="Paste", command=self.paste_text)
self.sub_menu3.add_command(label="About", command=self.show_about)
self.master.config(menu=self.menu_bar)
def new_file(self):
self.label.config(text="New file")
self.text_box.delete(1.0, tk.END)
def open_file(self):
self.label.config(text="Open file")
self.text_box.delete(1.0, tk.END)
def save_file(self):
self.label.config(text="Save file")
def cut_text(self):
self.label.config(text="Cut text")
self.text_box.delete(tk.SEL_FIRST, tk.SEL_LAST)
def copy_text(self):
self.label.config(text="Copy text")
self.master.clipboard_clear()
self.master.clipboard_append(self.text_box.get(tk.SEL_FIRST, tk.SEL_LAST))
def paste_text(self):
self.label.config(text="Paste text")
self.text_box.insert(tk.INSERT, self.master.clipboard_get())
def show_about(self):
self.label.config(text="About")
def set_text_box(self, text_box):
self.text_box = text_box
def set_label(self, label):
self.label = label
class App:
def __init__(self, master):
self.master = master
self.master.title("Multilevel Menu Bar with Submenu in GUI")
self.master.geometry("500x500")
self.label = tk.Label(self.master, text="")
self.label.pack()
self.text_box = tk.Text(self.master)
self.text_box.pack()
self.menu_bar = MenuBar(self.master)
self.menu_bar.set_text_box(self.text_box)
self.menu_bar.set_label(self.label)
if __name__ == "__main__":
root = tk.Tk()
app = App(root)
root.mainloop()
```
这个程序创建了一个具有多级菜单栏和多级子菜单的GUI窗口。每个子菜单都有不同的标签和文本框。当用户在菜单栏中选择一项时,程序将在窗口中显示相应的内容。这个程序使用了Tkinter的Menu和MenuCascade组件来创建多级菜单栏和子菜单。可以用相应的函数来处理每个菜单项的操作。
阅读全文