Python、Tkinter 库、涉及 GUI 的对象中的属性错误

Python, Tkinter library, Attribute Error in Object involving GUI

我正在为 class 制作一个非常简单的程序,其中涉及将 GUI 滑块的编号乘以另一个 GUI 滑块的编号。但是,出于某种原因,当我现在 运行 程序时,我得到一个 AttributeError 说 'gui' 对象没有属性 'slider1'。有任何想法吗?这是代码:

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()

程序中有一些语法错误,我已经注释掉了。以及你应该把方向放在秤上。这是代码。

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()

它对您不起作用的原因是没有该程序的实例。这就是我最后要做的。 Python 的垃圾收集收集使用 gui() 生成的实例,因此 Tkinter 无法引用 class 的实例。