Search code examples
pythonuser-interfaceobjecttkinterattributeerror

Python, Tkinter library, Attribute Error in Object involving GUI


I'm making a very simple program for class that involves multiplying the number of a GUI slider by another number of another GUI slider. But, for some reason when I run the program now, I get an AttributeError saying that 'gui' object has no attribute 'slider1'. Any ideas? Here's the code:

import tkinter
import random

class gui:
    def __init__(self):
       self.main_window = tkinter.Tk()

       #widgets
       self.__canvas = tkinter.Canvas(self.main_window,bg='white',width=300,height=10)

       self.label = tkinter.Label(self.main_window,text=('Product:',0))
       self.slider1 = tkinter.Scale(self.main_window,from_=0, to=12)
       self.slider2 = tkinter.Scale(self.main_window,from_=0, to=12)

       #packs
       self.__canvas.pack()

       self.label.pack(side='top')
       self.slider1.pack(side='left')
       self.slider2.pack(side='right')
       self.button = tkinter.Button(self.main_window,text='Click to multiply',command=self.multiply())
       self.button.pack(side='bottom')

       tkinter.mainloop()

   def multiply(self):
       x = int(self.slider1.get())
       y = int(self.slider2.get())
       num = x*y
       self.label.config(text=('Product:',num))

gui()

Solution

  • There is a few syntax error in the program, I commented those. As well as you should put orientations on the scales. Here is the code.

    import tkinter as tk
    
    class gui:
      def __init__(self):
        self.root = tk.Tk()
    
        # the widgets
        self.button = tk.Button(self.root, text="Multiply!", command=self.multiply)
        # you need no '()' for the function when inputing it in tkinter.
        self.label = tk.Label(self.root, text="Product: 0") # the '0 must be a string
        self.sliderX = tk.Scale(self.root, from_=0, to=12, orient=tk.HORIZONTAL)
        self.sliderY = tk.Scale(self.root, from_=0, to=12, orient=tk.VERTICAL)
        # add an orient to the scales.
    
        # now pack the widgets.
        self.button.pack()
        self.label.pack()
        self.sliderX.pack()
        self.sliderY.pack()
    
      def multiply(self):
        x = int(self.sliderX.get())
        y = int(self.sliderY.get())
        num = str(x * y) # need to turn the int to a string.
        self.label.config(text="Product: "+num)
    
    app = gui()
    app.root.mainloop()
    

    The reason it isn't working for you is because there is no instance of the program. This is what I do at the very end. Python's garbage collecting collects the instance made with gui() and so Tkinter can't reference an instance of the class.