每個人!我想使用 Tkinter 在 Python 中創建一個下拉選單。通常這很容易,但是如果我想創建一個顯示按鈕的下拉選單,您可以單擊它來執行特定功能怎么辦?一個很好的例子是,當您在大多數文本編輯器中單擊“檔案”時,它會顯示運行不同功能的“新建”、“打開”、“保存”等選項。我怎么做?
我沒有任何代碼可顯示,因為這不是錯誤,只是關于如何在 Tkinter 中創建按鈕下拉選單的一般問題。期待您的回答!非常感謝!
uj5u.com熱心網友回復:
這是如何完成的簡單示例
from tkinter import *
OPTIONS = [
"hello_world",
"save_file",
"create_object"
] #etc
def hello_world():
print("Hello World")
pass
def save_file():
print("File Saved")
pass
def create_object():
print("Object Created")
pass
def picker():
if variable.get() == "hello_world":
hello_world()
if variable.get() == "save_file":
save_file()
if variable.get() == "create_object":
create_object()
root = Tk()
root.geometry("100x100")
root.title("Dropdown demo")
variable = StringVar(root)
variable.set(OPTIONS[0]) # default value
om = OptionMenu(root, variable, *OPTIONS)
om.pack()
caller_button = Button(text="Call function", command=lambda: picker())
caller_button.pack(pady=10)
mainloop()
或者你可能需要這樣的東西:
import tkinter as tk
from tkinter import ttk, messagebox
def show_about_info():
messagebox.showinfo(
title="About",
message="Tkinter is GUI for Python programing language."
)
def quit_app():
root.destroy()
def example():
print("Example")
root = tk.Tk()
root.title("Menu dropdown example")
root.option_add("*tearOff", False)
main = ttk.Frame(root)
main.pack(fill="both", expand=True, padx=1, pady=(4, 0))
menubar = tk.Menu()
root.config(menu=menubar)
file_menu = tk.Menu(menubar)
help_menu = tk.Menu(menubar)
menubar.add_cascade(menu=file_menu, label="File")
menubar.add_cascade(menu=help_menu, label="Help")
file_menu.add_command(label="New", command=example)
file_menu.add_command(label="Save File", command=example)
file_menu.add_command(label="Open File", command=example)
file_menu.add_command(label="Close Tab", command=example)
file_menu.add_command(label="Exit", command=quit_app)
help_menu.add_command(label="About", command=show_about_info)
notebook = ttk.Notebook(main)
notebook.pack(fill="both", expand=True)
root.mainloop()
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/365152.html
