0

I just started learning tkinter couple of days back and was trying to implement drop down menu. I went through some of the materials online and was trying it. However, even after trying so hard, I am unable to get the desired output.

What I simply want is, if I select any option from the drop menu, it should print or pass value After click event only. My current code is printing the value before the click event and doing nothing after the click.

enter image description here

Here is the piece of code I am trying.

import tkinter as tk
import csv

class OC(tk.Tk):

    def __init__(self):
        tk.Tk.__init__(self)
        self.title("OC")
        self.geometry("300x400")

    def func(self, drop):
        label = tk.Label(self, text=drop.get())
        label.pack()

    def get_nifty_50_list(self):
        with open('nifty_50.csv', newline='') as csvfile:
            reader = csv.DictReader(csvfile)
            li = []
            for row in reader:
                li.append(row['Symbol'])
        return li

root = OC()

option_list = root.get_nifty_50_list()
expiry_list = ["May", "Jun", "Jul"]

dropVar = tk.StringVar()
dropVar.set(option_list[0])  # default choice
dropMenu = tk.OptionMenu(root, dropVar, *option_list)
dropMenu.pack()

button = tk.Button(root, text="Get Data", command=root.func(dropVar))
button.pack()

root.mainloop()

What's the wrong I am doing here?

Vikas Gupta
  • 10,779
  • 4
  • 35
  • 42
  • only issue I see is that You use `drop.get()` where `drop` is not defined in Your code, did You mean to use `dropVar.get()`? – Matiiss May 12 '21 at 17:22
  • I solved it by calling lambda just before calling the function. `button = tk.Button(root, text="Get Data", command=lambda:root.func(dropVar))` – Vikas Gupta May 13 '21 at 04:19

1 Answers1

1

Try this. I have substituted ["1","2","3"] instead of the csv file. The problem is you have give the first element of the list to the StringVar which it is printing.

You can substitute this function for your original func to get only one value at a time.

def func(self):
        
    for widget in root.winfo_children():
        widget.pack_forget()
    dropMenu.pack()
    self.label = tk.Label(self, text=dropVar.get())
    self.label.pack()
    button.pack()
import tkinter as tk


class OC(tk.Tk):

    def __init__(self,*args,**kwargs):
        tk.Tk.__init__(self,*args,**kwargs)
        self.title("OC")
        self.geometry("300x400")

    def func(self):
        label = tk.Label(self, text=dropVar.get())
        label.pack()

    

root = OC()

option_list = ["1","2","3"]
expiry_list = ["May", "Jun", "Jul"]

dropVar = tk.StringVar()
dropVar.set(option_list[0])  # default choice
dropMenu = tk.OptionMenu(root, dropVar, *option_list)
dropMenu.pack()

button = tk.Button(root, text="Get Data", command=root.func)
button.pack()
root.mainloop()