Tkinter 中 threading.Thread 与 mainloop 的用法问题
这个 AssertionError 是 threading.Thread 的构造参数用错造成的,和 Tkinter 内部 C 实现没有直接关系。Thread 的第一个位置参数是 group,不是 target。所以 threading.Thread(root.mainloop) 和 threading.Thread(Game.UpdateBoard) 会把函数传给 group,触发 assert group is None 断言,错误信息是 group argument must be None for now。应写成 threading.Thread(target=...)。另外,即使这样改,也不建议把 root.mainloop() 放进后台线程,更不要在后台线程里直接更新 Tkinter 控件。
报错原因
threading.Thread 的常见签名如下:
threading.Thread(group=None, target=None, name=None, args=(), kwargs=None)
group 目前必须为 None。第一个位置参数就是 group,所以:
t1 = threading.Thread(root.mainloop)
t2 = threading.Thread(Game.UpdateBoard)
等价于把 root.mainloop 和 Game.UpdateBoard 当作 group 传入,Python 在构造函数中断言失败。正确的参数写法是:
t1 = threading.Thread(target=root.mainloop)
t2 = threading.Thread(target=Game.UpdateBoard)
这样只修正了参数错误,Tkinter 的线程安全问题仍然存在。
另外,原代码里 t2.start() 后又直接调用了 Game.UpdateBoard(),可能让更新循环同时跑两份;UpdateBoard 仍然用 while True 加 time.sleep,不适合直接放在 GUI 线程里。
Tkinter 的线程限制
Tkinter/Tcl 通常不是线程安全的。比较可靠的做法是:
- 创建
Tk()、调用mainloop()、操作Canvas等 GUI 对象,都在主线程完成。 - 后台线程只处理计算、IO、阻塞等待等非 GUI 工作。
- 后台线程需要更新界面时,不要直接调用
canvas.itemconfig。可以把数据放进queue.Queue,由主线程用root.after()轮询并更新。
root.mainloop() 本身就是主事件循环,通常只在主线程调用一次。把它放到另一个线程里,再让主线程做其他循环,容易出现事件循环和 GUI 调用跨线程的问题。
推荐改法:用 after 驱动游戏循环
这种定时更新棋盘的场景,优先用 root.after(),不要用 threading.Thread。示例结构如下:
import tkinter as tk
import random as rand
root = tk.Tk()
root.geometry('400x960')
class Tetris:
def __init__(self, root):
self.root = root
self.canvas = tk.Canvas(root, width=400, height=960, bg='#00FF00')
self.canvas.pack()
self.block_active = False
self.current_block = None
self.grid_squares = {}
self.rect_ids = {}
self.block_templates = {
't_block': [[False, True, False, False], [False, True, True, True]],
'right_L': [[False, True, True, True], [False, False, False, True]],
'left_L': [[False, True, True, True], [False, True, False, False]],
'o_block': [[False, True, True, False], [False, True, True, False]],
'line_block': [[False, False, False, False], [True, True, True, True]],
'right_Z': [[False, False, True, True], [False, True, True, False]],
'left_Z': [[False, True, True, False], [False, False, True, True]]
}
self.possible_blocks = [
't_block', 'right_L', 'left_L', 'o_block',
'line_block', 'right_Z', 'left_Z'
]
for row in range(24):
for col in range(10):
rect_id = self.canvas.create_rectangle(
col * 40, row * 40, col * 40 + 40, row * 40 + 40,
fill='#777777', outline='white'
)
self.rect_ids[(row, col)] = rect_id
self.grid_squares[(row, col)] = False
def start(self):
self.update_board()
def update_board(self):
if not self.block_active:
self.current_block = rand.choice(self.possible_blocks)
for i in range(2):
for k in range(4):
self.grid_squares[(i, k + 4)] = self.block_templates[self.current_block][i][k]
self.block_active = True
self.change_board_state()
self.root.after(750, self.update_board)
def change_board_state(self):
for row in range(24):
for col in range(10):
if self.grid_squares[(row, col)]:
color = '#0000FF'
else:
color = '#777777'
self.canvas.itemconfig(self.rect_ids[(row, col)], fill=color)
game = Tetris(root)
game.start()
root.mainloop()
这个版本不再用 time.sleep,update_board 由 after 在主线程调度,不会阻塞 GUI 事件循环;canvas.itemconfig 也始终在主线程执行。
如果必须使用后台线程
如果确实要用后台线程,可以让它做耗时逻辑,但结果只能通过队列交给主线程:
import queue
import threading
ui_queue = queue.Queue()
def worker():
while True:
# 这里做非 GUI 计算
result = do_some_work()
ui_queue.put(('update', result))
def poll_queue():
while not ui_queue.empty():
msg = ui_queue.get()
# 在这里调用 canvas.itemconfig 等 GUI 方法
root.after(50, poll_queue)
threading.Thread(target=worker, daemon=True).start()
root.after(50, poll_queue)
root.mainloop()
这里后台线程不碰 Tkinter 控件,GUI 更新都在主线程完成。
其他注意事项
threading.Thread要写target=,不要依赖位置参数。- 不要同时
t2.start()又调用Game.UpdateBoard(),否则可能启动多个更新循环。 keyboard.wait会阻塞;如果放在 GUI 线程或after回调里,界面会卡住。可以用 Tk 的bind绑定按键:root.bind('<Right>', lambda e: game.move_right())。- 如果确实需要在后台监听键盘,把事件写入队列,再让主线程处理界面变化。
- Tkinter 程序通常以
root.mainloop()结束主流程,不要在它后面再启动重复的 GUI 循环。
备注:内容仅供参考。
