TypeError: 不支持的操作数类型(s) for -: 'list' 和 'list' 在 Tkinter 回调中异常

-2 投票
2 回答
46 浏览
提问于 2025-04-14 15:22
dic = ['a','b','c','1']
global is_on
global dic
def switch():
    if is_on:
        letters.config(bg='red')
        dic = dic - ['a','b','c']
        is_on = False
    else:
        letters.config(bg='green')
        dic = dic + ['a','b','c']
        is_on = True

我正在尝试从一个变量列表中删除一些项目,这个列表我稍后需要用来做随机选择的功能,但我一直遇到这个错误:

类型错误:不支持的操作数类型:'列表'和'列表'

我想做的是从列表中删除a、b、c,但又能在之后把它们加回来。

2 个回答

-2

在Tkinter中,如果你看到“TypeError: unsupported operand types for +: 'list' and 'list'”这个错误,通常是因为你试图用‘+’号把两个列表合在一起。要解决这个问题,你需要确保在处理列表时使用了正确的数据类型和操作方法。你可能需要把列表转换成可以合并的类型,或者使用其他方法,比如list.extend()或list.append()来合并列表。检查一下你的代码,确保列表操作是正确的,这样就能避免这个错误了。

-1

从列表中删除元素不是那么简单。如果你试图用一个列表减去另一个列表,程序会报错,提示不支持这种操作。比如:

>>> list = ['a', 'b', 'c']
>>> print(list - ['a','c'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'list' and 'list'

你可以使用numpy这个库来实现列表的减法。在Python 3.9中,操作大概是这样的:

>>> import numpy as np
>>> li = ['a', 'b', 'c']
>>> print(np.setdiff1d(li, ['a', 'c']).tolist())
['b']

撰写回答