【问题标题】:Using a Tkinter button input to pass as argument使用 Tkinter 按钮输入作为参数传递
【发布时间】:2023-02-07 05:53:06
【问题描述】:

我正在使用 tkinter 创建一个选项菜单,其中选择一个选项将调用特定于每个选项的函数。但是,我无法弄清楚该怎么做。

这是当前正在使用的代码。

import pandas as pd
import os 
import matplotlib.pyplot as plt 

#below code imports file needed at the moment
import tkinter as tk
from tkinter import *
from tkinter import filedialog
import pandas as pd
import os 
import matplotlib.pyplot as plt 

root = tk.Tk()
root.withdraw()

file_path = filedialog.askopenfilename() #will open file from any location, does not need to be in the same place as the code script 
df = pd.read_csv(file_path) 
df.rename(columns={'Unnamed: 0':'Type'}, inplace=True) #renames the first unnamed column to type (drug available (DA) or not available (NA)
df.dropna(how = 'all', axis = 1, inplace = True) #drops the empty column present in each dataset, only drops it if the whole column is empty 

##plotting functions for both active and inactive pokes
def ActivePokes(df): 
    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(df): 
    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(df): 
    if variable == options[1]:
        button[command] = ActivePokes(df)
    elif variable == options[2]: 
        button[command] = InactivePokes(df)
    else: 
        print("Error!")

options = [ "Choose Option",
           "1. Active pokes, Drug Available and No Drug Available sessions", 
           "2. Inactive pokes, Drug Available and No Drug Available sessions"]
button = Tk()
button.title("Dialog Window")

button.geometry('500x90')
variable = StringVar(button)
variable.set(options[0]) #default value, might change and edit as time passes 
option = OptionMenu(button, variable, *options, command = show)
option.pack()
button.mainloop()

我知道 show() 函数是问题所在,但我不完全确定如何纠正它。

【问题讨论】:

  • 你不能同时做root = tk.Tk()button = Tk()。你只为整个脚本写一个tk。

标签: python tkinter tkinter-button


【解决方案1】:

第一个问题,您创建了一个名为root 的tk 实例,然后又创建了另一个名为button 的实例,为什么?也许您希望按钮成为 tk.Button 而不是 tk 实例?不确定这里的意图是什么。

其次,您要为按钮更改的 command 变量是什么? (button[command])。如果按钮在 tk.button 的位置,那么也许您想执行 button['command'] = ...,但是,如果打算调用 pokes 函数,为什么不立即调用它们呢?

第三个问题在这里:

def show(df):
    if variable == options[1]:
        button[command] = lambda: ActivePokes(df)
    elif variable == options[2]:
        button[command] = lambda: InactivePokes(df)
    else:
        print("Error!")

variable 更改为variable.get()

【讨论】:

    【解决方案2】:

    其他 cmets 和答案解决了创建两个 Tk 对象以及使用 .get()StringVar 的问题。

    command = show 回调传递了所选项目的字符串值。在您的 show( df ) 中,当从 Optionmenu 调用时,df 将等于其中一个选项。它不会是熊猫数据框。下面的纯 tkinter 示例。

    import tkinter as tk
    
    root = tk.Tk()
        
    root.geometry( '100x100' )
    
    var = tk.StringVar( value = 'Option A' )
    
    def on_choice( chosen ):
        """  The callback function for an Optionmenu choice.
                chosen: The text value of the item chosen. 
        """
        print( chosen, end = "  :  " )
        print( ' or from the StringVar: ', var.get() )
    
    opt_list = [ 'Option A', 'Option B', 'Option C' ]
    
    options = tk.OptionMenu( root, var, *opt_list, command = on_choice )
    
    options.grid()
    
    root.mainloop()
    

    【讨论】:

      猜你喜欢
      • 2022-11-05
      • 2015-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-22
      • 2021-01-20
      • 2014-05-08
      • 1970-01-01
      相关资源
      最近更新 更多