简体   繁体   中英

What causes an exception in Tkinter callback?

I'm trying to make a program that you can add infinite rooms to, so all of my code is built around using one variable to deduce which room is which. However when I run it, it gives me an error that doesn't directly reference any one line in my code, and since I'm a pretty new programmer, I don't know what it means. Also my code is pretty all over the place and incomplete. Thanks for any help!

The error

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\SCA0023\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 1892, in __call__
    return self.func(*args)
TypeError: 'NoneType' object is not callable

The Code

from tkinter import *

root = Tk()


class Room:
    def __init__(self, items):
        self.objects = []
        self.objects.append(items)

    def list(self):
        print(self.objects)


def addkitchenmenu(r): #add a new option menu attributed to a new room
    globals()[f'kitchenvar_{r}'] = StringVar(root)
    globals()[f'kitchenvar_{r}'].set("Add an appliance")
    globals()[f'kitchenvar_{r}'].trace('w', applianceadd(r))
    kitchenitems = ['Kettle', 'Toaster']
    globals()[f'appliancelist_{r}'] = OptionMenu(root, globals()[f'kitchenvar_{r}'], *kitchenitems).pack()
    addkitchen(r)


def applianceadd(r): #add a new room
    globals()[f'kobjects_{r}'] = []
    globals()[f'kobjects_{r}'].append(globals()[f'kitchenvar_{r}'].get())
    items = globals()[f'kobjects_{r}']
    globals()[f'kroom_{r}'] = Room(items)
    globals()[f'kroom_{r}'].list()


def addkitchen(r): #add an appliance
    globals()[f'addappliace{r}'] = Button(root, text='add appliance', command=lambda: applianceadd(r))


def newkitchencheck(): #find the next name for a room that isn't taken
    varnotfound = True
    a = 0

    while varnotfound:
        if f'kroom{a}' in globals():
            a += 1
        else:
            r = a
            varnotfound = False
            addkitchenmenu(r)


addroombutton = Button(root, text="add kitchen", command=newkitchencheck)
addroombutton.pack()

root.mainloop()

You are passing result of applianceadd(r) (which is None) to .trace(). Change to .trace("w", lambda *_: applianceaddr(r)).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM