MisterButter
MisterButter

Reputation: 797

Use user input as function arguments in tkinter

I want to use the users inputs in e1, e2, e3, e4 as class arguments for the class Data(). I tried creating a function get_args() but it just returns empty stings since action by the user has to be taken to actually show the inputs. What is the best way of taking user input and using them as funtion arguments?

d = Data()




import tkinter as tk
from hist import Data

def quit(root):
    root.destroy()

#def get_args():
    #return e1.get(), e2.get(),e3.get(), e4.get()

def show_entry_fields():
    print("Ticker: %s\nStart Date: %s\nEnd Date: %s\nBasis: %s" % (e1.get(), e2.get(),e3.get(),e4.get()))


root = tk.Tk()



tk.Label(root, text="Ticker").grid(row=0)
tk.Label(root, text="Start Date").grid(row=1)
tk.Label(root, text="End Date").grid(row=2)
tk.Label(root, text="Basis").grid(row=3)

e1 = tk.Entry(root)
e2 = tk.Entry(root)
e3 = tk.Entry(root)
e4 = tk.Entry(root)


e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
e3.grid(row=2, column=1)
e4.grid(row=3, column=1)



#Data = Data(get_args())
#Ticker = d.get_histocial_prices()

tk.Button(root, text='Show', command=show_entry_fields).grid(row=4, column=1, sticky=tk.W, pady=4)


tk.Button(root, text='Quit', command=root.quit).grid(row=4, column=0, sticky=tk.W, pady=4)
#tk.Button(root, text='Show', command=Ticker).grid(row=4, column=2, sticky=tk.W, pady=4)
root.mainloop()

Upvotes: 0

Views: 1227

Answers (1)

Masoud
Masoud

Reputation: 1280

You can define variables as global in get_args() function as:

import tkinter as tk
from hist import Data

def get_args():
    global ticker, start_date, end_date, basics

    ticker = e1.get()
    start_date = e2.get()
    end_date = e3.get()
    basics = e4.get()
    # print variables and initialize Data
    init_data()

def init_data():
    print("Ticker: %s\nStart Date: %s\nEnd Date: %s\nBasis: %s" % (ticker, start_date,end_date,basics))
    global d
    d = Data(ticker, start_date, end_date, basics)

root = tk.Tk()

tk.Label(root, text="Ticker").grid(row=0)
tk.Label(root, text="Start Date").grid(row=1)
tk.Label(root, text="End Date").grid(row=2)
tk.Label(root, text="Basis").grid(row=3)

e1 = tk.Entry(root)
e2 = tk.Entry(root)
e3 = tk.Entry(root)
e4 = tk.Entry(root)

e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
e3.grid(row=2, column=1)
e4.grid(row=3, column=1)

tk.Button(root, text='get entries', command=get_args).grid(row=4, column=1, sticky=tk.W, pady=4)

root.mainloop()

Upvotes: 1

Related Questions