python - 如何立即获得标签更新而不是等待另一个回调事件?
问题描述
import tkinter as tk
import smtplib
from word_length import find_word_length
class Email_app(tk.Frame):
def __init__(self, master = None):
tk.Frame.__init__(self, master)
self.create_widget()
def create_widget(self):
self.myLabel = tk.Label(root, text = "Email app", width = 50).grid()
self.myUsername = tk.Label(root, text = "Username").place(x = 10, y = 30, width = 70, height = 20)
self.myUserEntry = tk.Entry(root)
self.myUserEntry.place(x = 90, y = 30, width = 200, height = 20)
self.myPassword = tk.Label(root, text = "Password").place(x = 10, y = 60, width = 70, height = 20)
self.myPasswordEntry = tk.Entry(root)
self.myPasswordEntry.place(x = 90, y = 60, width = 200, height = 20)
self.To = tk.Label(root, text = "Destination").place( x = 10, y = 90, width = 70, height = 20)
self.To_entry = tk.Entry(root)
self.To_entry.place(x = 90, y = 90, width = 200, height = 20)
#from here is about the entry box
self.myEntry = tk.Text(root)
self.myEntry.bind('<Key>',lambda x: self.callback())
self.myEntry.place(x = 10, y = 120, width = 430, height = 460)
self.strVal = tk.StringVar()
self.strVal.set("Word: 0 word")
self.Textlength = tk.Label(root, textvariable = self.strVal, width = 70)
self.Textlength.place(x = 320, y = 50, width = 120, height = 30)
self.myBtn = tk.Button(root,text = "Submit email", command = self.on_release)
self.myBtn.place(x = 350, y = 600)
def on_release(self):
Username = self.myUserEntry.get()
Password = self.myPasswordEntry.get()
Destination = self.To_entry.get()
text = self.myEntry.get('1.0',tk.END)
self.myEntry.delete('1.0', tk.END)
self.strVal.set("Word: 0 word")
try:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login(Username,Password)
server.sendmail(Username,Destination,text)
except:
print('Something went wrong')
def callback(self):
length = find_word_length(self.myEntry.get('1.0',tk.END))
if length == 1 or length == 0:
self.strVal.set(f"Word: {length} word")
elif length > 1:
self.strVal.set(f"Word: {length} words")
root = tk.Tk()
root.geometry("450x650")
root.resizable(width=False, height=False)
Email_app_main = Email_app(root)
Email_app_main.mainloop()
我正在创建一个简单的电子邮件应用程序,用户可以在其中使用 smtplib 模块登录然后发送电子邮件。我实现了一个回调函数,不断检查用户在文本输入框中输入了多少字,然后在 self.Textlength 标签中更新它。一切正常,但我注意到标签没有在同一个回调事件上更新,我需要再次触发回调事件来更新标签文本。有没有办法在同一个回调事件上立即更新标签而不等待另一个?
解决方案
问题是<Key>
绑定是在条目文本更新之前执行的,这与<KeyRelease>
. 请改为在您的代码中使用self.myEntry.bind('<KeyRelease>',lambda x: self.callback())
。希望这会有所帮助!
推荐阅读
- regex - 如何制作正则表达式来验证用户名
- c++ - 在 C++ 中的函数参数中使用任何类型
- javascript - 如何使用 JavaScript 在每行的开头和结尾添加文本
- python - 求解齐次坐标 (x,y,z,w) 中两个 3D 向量的叉积
- c++ - 在存储在 std::vector 中的小端和大端值之间进行转换
- reactive-programming - 使用 2 个嵌套订阅返回 Mono/Flux
- c# - 有什么简单的方法可以在不进行反序列化的情况下从 json 中找出最低值 c#
- swift - \。Swift 中的运算符
- installation - 运行 Anaconda3 安装 bash 脚本失败
- selenium - 使用 xPath (Selenium, Python) 找到 Tweet 'like' 按钮