python-3.x - Changing order of execution in python
问题描述
I have recently started programming and written a fairly simple program. But stuck at a point. My program does a very simple thing that when you click a button it will say a line and shows that text on the screen. But it is speaking the text first and then displays it on the screen but I want its reverse, i.e it should first display it on the screen and then speak the text.
from tkinter import *
import pyttsx3
root = Tk()
def speak():
engine = pyttsx3.init()
say = "I am speaking."
text.insert("0.0", say)
engine.say(say)
engine.runAndWait()
text = Text(root)
text.pack()
btn = Button(root, text="speak", command=speak)
btn.pack()
root.mainloop()
Thanks in advance.
解决方案
It is because engine.runAndWait()
blocks the application, and so text box cannot be updated by tkinter mainloop until the speaking completed.
You can call text.update_idletasks()
to force tkinter to update the text box before the speaking:
engine = pyttsx3.init() # initialize only once
def speak():
say = "I am speaking."
text.insert("0.0", say)
text.update_idletasks() # force tkinter update
engine.say(say)
engine.runAndWait()
推荐阅读
- java - google calendar api 说 400 bad request 由于无效值(会议属性)
- node.js - Twilio autopilot whatsapp 使用 nodeJS 发起与电话的对话
- python - Python 线程无法启动
- phoenix-framework - 如何使用 Phoenix LiveView 处理表单文件?
- iis - IIS 10.0 SSI 错误:已为此虚拟路径禁用 #EXEC 调用
- pine-script - 在 Pine Script Tradingview 中使用 Security() 的 EMA 问题
- datetime - Pyspark 通过列表理解从日期时间获取时间属性
- javascript - 如何从此 JSON 创建图表?
- python-3.x - 绘制 Seaborn 情节并添加图例
- python-2.7 - 添加将字典附加到另一个 multiprocessing.managers.DictProxy 中的列表