You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Tkinter选项菜单选择后调用对应函数的实现问题求助

修正后的代码实现
import pandas as pd
import matplotlib.pyplot as plt 
import tkinter as tk
from tkinter import filedialog, StringVar, OptionMenu

# 读取数据
root = tk.Tk()
root.withdraw()

file_path = filedialog.askopenfilename()
df = pd.read_csv(file_path) 
df.rename(columns={'Unnamed: 0':'Type'}, inplace=True)
df.dropna(how='all', axis=1, inplace=True)

## 绘图函数
def ActivePokes(): 
    plt.rcParams["figure.figsize"] = (12,7.5)
    df.plot()
    plt.xticks(range(0, len(df.Type)), df.Type)
    plt.ylabel("Number of Active Pokes")
    plt.xlabel("Sessions")
    plt.title("Number of Active Pokes vs Drug Availability")
    plt.show()
    
def InactivePokes(): 
    plt.rcParams["figure.figsize"] = (12,7.5)
    df.plot()
    plt.xticks(range(0, len(df.Type)), df.Type)
    plt.ylabel("Number of Inactive Pokes")
    plt.xlabel("Sessions")
    plt.title("Number of Inactive Pokes vs Drug Availability")
    plt.show()
    
def show(selected_option): 
    if selected_option == options[1]:
        ActivePokes()
    elif selected_option == options[2]: 
        InactivePokes()
    # 默认选项不执行操作

options = [
    "Choose Option",
    "1. Active pokes, Drug Available and No Drug Available sessions", 
    "2. Inactive pokes, Drug Available and No Drug Available sessions"
]

# 创建主窗口
main_window = tk.Tk()
main_window.title("Dialog Window")
main_window.geometry('500x90')

variable = StringVar(main_window)
variable.set(options[0])

option_menu = OptionMenu(main_window, variable, *options, command=show)
option_menu.pack()

main_window.mainloop()
关键修改说明
  • 清理冗余导入:删除重复导入的模块,保持代码简洁
  • 调整show函数参数:OptionMenu的command回调会自动传入当前选中的选项文本,show函数通过该参数判断用户选择
  • 直接调用目标函数:去掉错误的button[command]赋值逻辑,在show中直接调用对应绘图函数,避免函数提前执行
  • 简化绘图函数:利用全局变量df,绘图函数无需额外传参,简化调用逻辑
  • 优化窗口命名:将原button变量改为main_window,避免和控件名称混淆,语义更清晰

内容的提问来源于stack exchange,提问作者Hibah Mirza Chughtai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 19:20:47