Matt
Matt

Reputation: 3

how to get tkinter input outside of function within class

How do I get access to variables (ifrequency and iperiod) outside of the class?

import tkinter as tk
from tkinter import ttk

root = tk.Tk()

class Parameters:

    def __init__(self,master):

        tk.Label(master,text='frequency').grid(row=0)
        tk.Label(master,text='period').grid(row=1)
        
        self.options1 = ['D1', 'D2']
        self.options2 = ['daily', 'monthly']
        
        self.mycombo1 = ttk.Combobox(master, value=self.options1)
        self.mycombo1.bind("<<ComboboxSelected>>")
        self.mycombo1.grid(row=0, column=1)      
        
        self.mycombo2 = ttk.Combobox(master, value=self.options2)
        self.mycombo2.bind("<<ComboboxSelected>>")
        self.mycombo2.grid(row=1, column=1)        

        self.myButton = tk.Button(master, text="Go", command=self.clicker).grid(row=3,column=1)              
      
    def clicker(self):
        ifrequency = self.mycombo1.get()
        iperiod = self.mycombo2.get()
        return ifrequency, iperiod
    
p = Parameters(root)
   
root.mainloop()

print(p.ifrequency)

The code gives the error: "AttributeError: 'Parameters' object has no attribute 'ifrequency'" when running the final line.

For a bit of context, I have built some code to get output from an API. I want the user to be able to pick the inputs (e.g. frequency, period) using a form and then have the main program call the API and using these inputs. My API code works but I need to get the user inputs assigned to a variable. I can do it but that variable is stuck in the function/class and I can't figure out the correct way to get it out.

This is my first question here (usually someone else has asked before me) so apologies if I have made any mistakes. Many thanks in advance for your help!

Upvotes: 0

Views: 228

Answers (1)

Hadrian
Hadrian

Reputation: 927

ifrequency and iperiod are not assigned to self and are just in the function's local scope so they disappear after clicker returns, and since it is called by the tkinter button, it's return value dosn't do anything. so try changing clicker so it assigns them to self

    def clicker(self):
        self.ifrequency = self.mycombo1.get()
        self.iperiod = self.mycombo2.get()

Upvotes: 1

Related Questions