使用tkinter.Tk.wait_variable()触发_tkinter.TclError错误的问题
问题原因及解决方案
你遇到的_tkinter.TclError错误,是因为wait_variable方法要求传入tkinter内置的Variable类实例(比如IntVar、StringVar),而不是普通的Python变量。你当前用的self.action是普通变量,不符合方法的参数要求。
修正步骤:
- 初始化tkinter变量:在类的
__init__方法中,将self.action定义为tkinter.IntVar(),而不是普通变量。 - 修改赋值方式:在
set_action方法中,使用变量的set()方法赋值,而不是直接赋值。 - 修正wait_variable调用:在
play_hand方法中,直接传入self.action(此时是IntVar实例),后续判断时用get()方法获取变量值。
修改后的代码片段:
import tkinter as tk from tkinter import Button, Tk class CardsGui(): def __init__(self, game): self.window = Tk() # 初始化tkinter整数变量,用于存储动作 self.action = tk.IntVar() self.blackjack() self.window.mainloop() def set_action(self, action): print(action) # 使用set方法给tkinter变量赋值 self.action.set(action) def blackjack(self): self.action_buttons = [] # 注意:这里按钮文本是"Stand"但对应action=3,可根据实际需求调整 button_split = Button(text="Stand", command=lambda: self.set_action(3), width=10) button_split.grid(column=1, row=9, padx=20, pady=20) self.action_buttons.append(button_split) # 假设player_number和player是已定义的变量 player_number = 0 player = {} hand = self.play_hand(player_number, player) def play_hand(self, player_number, hand, AI=False): self.display_hand(player_number, hand) # 重置变量值为初始状态 self.action.set(None) # 传入tkinter变量实例 self.window.wait_variable(self.action) # 获取变量当前值 action_value = self.action.get() if action_value == 0: print("Stand") elif action_value == 1: print("Hit") elif action_value == 2: print("Double") elif action_value == 3: print("Split") def display_hand(self, player_number, hand): # 补充display_hand方法的实现(原代码未提供) pass
关键说明:
- tkinter的
Variable类是和Tcl解释器绑定的,wait_variable通过监听这类变量的变化来实现等待逻辑,普通Python变量无法被Tcl识别。 - 调用
wait_variable后,程序会暂停在这里,直到self.action的值被修改(比如按钮点击触发set_action),才会继续执行后续代码。
内容的提问来源于stack exchange,提问作者ElvisJr
相关产品推荐
相关产品推荐

