0

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!

1
  • Inside the clicker method, make sure the variables that you're assigning are attributes of the class. Instead of ifrequency, it should be self.ifrequency Commented Feb 7, 2021 at 15:07

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.