Skip to content
Advertisement

how to get value from def function before

i got a problem to run the python, for example code in below, because the code not sure to see because i am beginner for this,and its too long too, i give the same problem on my code

from tkinter import *
from tkinter import ttk

root = Tk()

root.title('app')

class calculate:
     def thefirst(self):
         y1 = 1

     def second(self):
         v1 = 5 - y1
         print(v1)

Button(root, text="GENERATE", command=second)

the problem is if i press the button for y1 not define

so i writte the code

from tkinter import *
from tkinter import ttk

root = Tk()

root.title('app')

class calculate:
     def thefirst(self):
         y1 = 1

     def second(self):
         for y1 from the first()
         v1 = 5 - y1
         print(v1)

Button(root, text="GENERATE", command=second)

but in my visual studio code got a red color problem, but the code is still not working to generate data, is my code wrong?

thank you

Advertisement

Answer

I see a few problems on your code:

  1. First of all, you need to define a constructor for your class __init__ to assign the default value to your attributes.

  2. You have to use self. for class attributes, otherwhise, the value will not be saved.

  3. You need to instantiate the class, because you have to reference the instance function, no the class function, because is not static.

    from tkinter import *
    from tkinter import ttk
    
    root = Tk()
    
    root.title('app')
    
    class calculate:
        def __init__(self):
            self.y1 = 1
    
        def second(self):
            v1 = 5 - self.y1
            print(v1)
    
    calc = calculate()
    Button(root, text="GENERATE", command=calc.second)
    

I recommend you to search on internet about OOP (Object Oriented Programming) on Python, and learn the basics.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement