我正在使用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()函数是问题所在,但我不完全确定如何纠正它。
2条答案
按热度按时间4nkexdtk1#
第一个问题,你已经创建了一个tk示例
root
,然后又创建了一个tk示例button
,为什么?也许你想让button成为一个tk.button而不是一个tk示例?不确定这里的意图是什么。第二,你想为button改变的
command
变量是什么?(button[command]
). if button where a tk.button,那么也许你想做button['command'] = ...
,但是,如果你想调用pokes函数,为什么不马上调用它们呢?第三个问题是:
将
variable
更改为variable.get()
nmpmafwu2#
其他注解和答案解决了创建两个
Tk
对象以及将.get()
与StringVar
一起使用的问题。command = show
回调函数会传递所选项目的字符串值。在你的show( df )
中,当从选项菜单调用时,df
会等于其中一个选项。它不会是一个Pandas Dataframe 。下面是纯tkinter示例。