0

I'm using tkinter to create an option menu, where choosing an option will call a function specific to each option. However, I'm unable to figure out exactly how to do that.

This is the code that is currently being used.

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()

I know the show() function is where the issue lies, but I'm not entirely sure how to rectify it.

2 Answers2

1

The other comments and answer address problems with creating two Tk objects and using .get() with a StringVar.

The command = show callback is passed the string value of the item chosen. In your show( df ) when called from the Optionmenu will have df equal to one of the options. It won't be a pandas dataframe. Pure tkinter example below.

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()
Tls Chris
  • 3,564
  • 1
  • 9
  • 24
0

First problem, you have created a tk instance called root, and then another one called button,why? perhaps you want button to be a tk.Button and not a tk instance? Not sure what is the intention here.

second, what is it command variable you want to change for button? (button[command]). if button where a tk.button, then perhaps you wanted to do button['command'] = ..., however, if the intention is to call the pokes functions why not calling them right away?

third problem is here:

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

change variable for variable.get()

mamg2909
  • 96
  • 4