You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Tkinter开发GUI时按钮绑定函数提前自动执行问题求助

问题解决说明

错误原因

Tkinter 按钮的command参数要求传入函数对象本身,你在代码中写的command=Do_test()带了函数调用括号,Python 解析到这行代码时就会立即执行Do_test函数,不会等到按钮被点击时触发。

修复方案

将按钮定义行的Do_test()后的括号删除即可,只传函数名本身。
另外原代码中使用的input()是命令行交互函数,在 GUI 程序中调用会导致界面无响应,建议替换为 Tkinter 自带的图形化输入组件,修复后的完整代码如下:

import pyttsx3
from openpyxl import load_workbook
from tkinter import *
from tkinter import simpledialog

def Do_test():
    i=0
    wb = load_workbook('words.xlsx')
    ws = wb.active
    for row in ws.values:
        for value in row:
            engine = pyttsx3.init()
            engine.say(value)
            engine.runAndWait()
            # 图形化弹窗输入,避免GUI卡死
            Ans = simpledialog.askstring("答案输入", "please enter the word")
            if Ans == value:
                print("Right")
            else:
                print("wrong")
                i = i+1
                wrong = value
                ws.cell(row=i, column=2, value=wrong)
    wb.save('result.xlsx')

root = Tk()
# 去掉Do_test后的括号,仅传入函数对象
myButton = Button(root, text="Run", command=Do_test)
myButton.pack()

root.mainloop()

内容的提问来源于stack exchange,提问作者Zehao Chen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 14:51:04