python 使用Tkinter按钮输入作为参数传递

9vw9lbht  于 2023-02-07  发布在  Python
关注(0)|答案(2)|浏览(313)

我正在使用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()函数是问题所在,但我不完全确定如何纠正它。

4nkexdtk

4nkexdtk1#

第一个问题,你已经创建了一个tk示例root,然后又创建了一个tk示例button,为什么?也许你想让button成为一个tk.button而不是一个tk示例?不确定这里的意图是什么。
第二,你想为button改变的command变量是什么?(button[command]). if button where a 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()

nmpmafwu

nmpmafwu2#

其他注解和答案解决了创建两个Tk对象以及将.get()StringVar一起使用的问题。
command = show回调函数会传递所选项目的字符串值。在你的show( df )中,当从选项菜单调用时,df会等于其中一个选项。它不会是一个Pandas Dataframe 。下面是纯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()

相关问题