簡體   English   中英

python tk 不同的功能取決於所選的下拉列表項

[英]python tk different functions depending on drop down list item selected

我試圖根據用戶選擇的內容在下拉列表中調用不同的 function。 例如,假設我想要調用 2 個函數,具體取決於是否在下拉列表中選擇了 function1 或 function2。

這是我使用的 tk 調用:

from TK import *

這就是我編寫選項菜單的方式:

Dropdown = OptionMenu("function1","function2",command = run_a_function)

無論選擇哪個選項,它都會運行相同的 function。

有沒有辦法將 function 分配給選項菜單中的不同選項?

編輯:添加了兩個功能。

這是你想要的嗎?

import tkinter as tk

root = tk.Tk()

a = tk.StringVar()
a.set("default")

var = tk.StringVar(root)
var.set("Select")

 
def _this_what_you_wanted():
    print(f'Is this what you wanted?')

    
def _this_is_second_function():
    print(f'this is second function')
    
def run_a_function(x):

  if x == "function1":
      _this_what_you_wanted()

  else:
      a.set("function2")
      _this_is_second_function()

opt = tk.OptionMenu(root, var, "function1","function2", command = run_a_function)
opt.pack()

root.mainloop()

有沒有辦法將 function 分配給選項菜單中的不同選項?

嚴格來說,沒有。 您只能將單個 function 定義到OptionMenu 但是,單個 function 可以使用 map 來確定哪個 function 可以運行。

這是一個創建字典的示例,其中包含應出現在選項菜單中的函數和名稱。 當綁定到選項菜單的 function 運行時,它獲取選項菜單的值,使用它在字典中查找 function,然后運行該 function。

import tkinter as tk

def func1():
    label.configure(text="func1 called")

def func2():
    label.configure(text="func2 called")


functions = {
    "function 1": func1,
    "function 2": func2,
}

def run_a_function(*args):
    func_name = function_var.get()
    func = functions.get(func_name, None)
    func()

root = tk.Tk()
root.geometry("400x200")
function_var = tk.StringVar(value="Choose a function")

dropdown = tk.OptionMenu(root, function_var, *functions.keys(), command=run_a_function)
dropdown.configure(width=15)
label = tk.Label(root, text="")

dropdown.pack(side = "top")
label.pack(side="top", fill="x", pady=10)

root.mainloop()

綜上所述, OptionMenu只是一個Menubutton和一個 `Menu。 您可以創建自己的小部件並直接將功能分配給下拉列表中的項目。

這是一個例子:

import tkinter as tk

def func1():
    label.configure(text="func1 called")

def func2():
    label.configure(text="func2 called")

root = tk.Tk()
root.geometry("400x200")

dropdown = tk.Menubutton(root, text="Choose a function", indicatoron=True, width=15)
dropdown_menu = tk.Menu(dropdown)
dropdown.configure(menu=dropdown_menu)
dropdown_menu.add_command(label="function 1", command=func1)
dropdown_menu.add_command(label="function 2", command=func2)
label = tk.Label(root, text="")

dropdown.pack(side = "top")
label.pack(side="top", fill="x", pady=10)

root.mainloop()

請注意,上面的示例從未更改出現在菜單按鈕上的 label。 如果您願意,可以添加代碼來執行此操作。 為了使示例簡單,我將其遺漏了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM