Consistently getting above stated error when I try to call a function using the tkinter button.
So here is the example code used for this particular issue.
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):
df.plot(figsize = (12,7.5),
xlabel = 'Number of active pokes', ylabel = 'Sessions',
title = 'Number of Active Pokes vs Drug Availability')
plt.xticks(range(0,len(df.Type)), df.Type)
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.get() == options[1]:
ActivePokes(df)
elif variable.get() == options[2]:
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()
However, the error I keep receiving is this:
Is there any way this can be rectified and I can still produce the graphs needed while using the tkinter button?
The option Menu automatically passes the selected option to the command. Since you named the argument df
in the function, the logical connection is df = contentained_string_of_optionmenu
in the namespace of your function. However, since df
origionally is a dataframe, you should just have to rename the argument/parameter of your function like:
def show(opt):
In addition it makes the StringVar
useless since you can do:
if opt == options[1]:
ActivePokes(df)
elif opt == options[2]:
InactivePokes(df)
else:
print("Error!")
You might also choose to clear the argument df
elsewhere since it's in the global namespace.