Tkinter报错:can't invoke 'bind' command: application has been destroyed 求助
问题与解决方案
报错信息
运行代码时触发错误:
can't invoke "bind" command: application has been destroyed
即使仅调用两行messagebox代码也会出现该问题:
from tkinter import messagebox launch = messagebox.showinfo("oops", "No such state", icon="warning")
完整代码
import turtle from turtle import Turtle, Screen from score import Score import pandas from tkinter import messagebox turtle.colormode(255) turtle.penup() turtle.hideturtle() writer = Turtle() writer.hideturtle() writer.penup() screen = turtle.Screen() def button(): butt = Turtle() butt.penup() butt.hideturtle() butt.speed("fastest") butt.color(66, 184, 213) butt.goto(-80, -50) butt.pendown() butt.fillcolor(241, 218, 160) butt.begin_fill() butt.forward(160) butt.left(90) butt.forward(80) butt.left(90) butt.forward(160) butt.left(90) butt.forward(80) butt.end_fill() butt.penup() butt.goto(-65, -25) butt.pendown() butt.write(arg="Start Game", move=False, font=("Times New Roman", 30, "normal")) button() def game(): screen.clear() # 修正:这里是方法调用,不是赋值 screen.title("U.S. States Game") image = "blank_states_img.gif" screen.addshape(image) turtle.shape(image) score = Score() turtle.setup(730, 500) in_d = "50_states.csv" data = pandas.read_csv(in_d) guessed_states = [] state = data["state"].tolist() xcor = data["x"].tolist() ycor = data["y"].tolist() num_of_states = len(state) while score < 50: answer_state = screen.textinput(title='Guess the state', prompt="What's the state's name?").capitalize() if answer_state not in state and answer_state in guessed_states: launch = messagebox.showinfo("oops", "You already guessed it!", icon="warning") elif answer_state not in state: launch = messagebox.showinfo("oops", "No such state", icon="warning") for i in state: if i == answer_state: position = state.index(answer_state) x_cor = int(xcor[position]) y_cor = int(ycor[position]) location = (x_cor, y_cor) writer.goto(location) writer.write(arg=answer_state, move=False, font=("Times New Roman", 10, "normal")) score.increase_score() state.remove(answer_state) guessed_states.append(answer_state) def butt_click(x, y): if x > -50 and x < 50 and y > -50 and y < 65: game() turtle.onscreenclick(butt_click, 1) turtle.listen() turtle.done() # 移除这一行,避免冲突 # screen.exitonclick()
问题根源
- 主循环重复绑定冲突:
turtle.done()会启动tkinter主循环并保持窗口运行,之后的screen.exitonclick()会尝试给已进入销毁流程的窗口绑定退出事件,导致后续调用messagebox时,tkinter应用已处于无效状态。 - 标题设置错误:原代码中
screen.title = ("U.S. States Game")是赋值操作,不是调用标题设置方法,无法正确修改窗口标题。
修复步骤
- 删除末尾的
screen.exitonclick(),保留turtle.done()负责主循环和窗口生命周期管理。 - 将
screen.title = ("U.S. States Game")改为screen.title("U.S. States Game"),正确调用标题设置方法。
额外优化建议
可以用pandas的直接查询替代循环收集数据,提升效率:
# 替换原有的state、xcor、ycor循环收集 state = data["state"].tolist() xcor = data["x"].tolist() ycor = data["y"].tolist() # 或者在匹配状态时直接查询坐标 if answer_state in state: state_row = data[data["state"] == answer_state].iloc[0] x_cor = state_row["x"] y_cor = state_row["y"] # 后续写入逻辑不变
内容的提问来源于stack exchange,提问作者tensai
相关产品推荐
相关产品推荐

