0

I'm trying to create a GUI using tkinter. My objective is really simple, everytime I update the value of the spinbox a label should appear with the text 'the value is (value)'. This is a small code sample, I need to create a class for the full code, but an error appears every time I update the spinbox widget.

First I import the libraries and create a class:

import tkinter as tk
from tkinter import ttk

class testclass:

    def __init__(self):
       
        self.Var = tk.StringVar(value=5)
        self.widget = ttk.Spinbox(root,from_=0,to=10,textvariable=self.Var)
        self.widget.pack()
        
        self.Var.trace_add('write', self.trace_test)
        
    def trace_test(self):
        self.text = ttk.Label(root, text = 'the value is '+str(self.Var.get()))
        self.text.pack()

Then I call my GUI:

root = tk.Tk()

test1 = testclass()

root.mainloop()

The program works fine but when I change the value of the spinbox the next error appears:

TypeError: testclass.trace_test() takes 1 positional argument but 4 were given

I can't find any solution to this problem. I don't undestand why it says that 4 arguments were given.

Toni
  • 1

1 Answers1

2

The trace_add function in tkinter attempts to pass four arguments to the defined callback function (see this answer). Your callback function, however, only takes in one argument, namely the class instance that's calling the function (self).

If you don't care about the arguments passed to the callback function (which I doubt you do), you can simply accept them and then not do anything with them like this:

def trace_test(self, *args):
    self.text = ttk.Label(root, text = 'the value is '+str(self.Var.get()))
    self.text.pack()
M. Chak
  • 530
  • 3
  • 13