Tkinter开发WhatsApp自动化程序运行报错修复(保留Text组件)
故障根因
两处Text组件相关的报错由3个Tkinter接口用法错误导致:
Text组件不支持textvariable参数,该参数仅适用于Entry等单行输入组件,传入后会直接抛出_tkinter.TclError导致程序启动失败Text组件的内容读写接口索引规则和Entry不同:insert、get方法都需要使用行号.列号格式的位置参数,原代码用insert(0, 内容)、无参调用get()都会触发接口报错- 原代码同时对组件调用
grid和place布局方法存在逻辑冲突,保留原设计的place绝对布局即可,删除冗余grid调用不影响原有视觉样式
修复说明
- 完全保留两个
Text组件的设计,未替换为Entry - 所有原有功能:实时本地时间刷新、24小时制定时发送、多语言标签、原布局位置/配色/样式全部保留
- 给两个Text组件补充适配原布局的高度参数,避免默认高度过大撑乱界面
- 修正Text组件内容读写的索引参数,保证号码、消息内容可以正常读取传递给pywhatkit接口
修复后可直接运行的完整代码
from tkinter import * import pywhatkit import time root = Tk() root.title("whatsapp") root.geometry('405x1000') root.resizable(width=0, height=0) label = Label(root, text="Whatsapp Automation", font='bold', width=40 , fg='white', bg='black', padx=10, pady=13) label.place(x=10, y=10) # 号码输入区 label=Label(root, text="whatsapp numbers", font=10 , fg="white", bg="black") label.place(x = 10, y=90) number_str = StringVar() # 移除Text组件不支持的textvariable参数,补充height参数适配单行输入布局 entry1 = Text(root,width=30, bd=6, font=14, borderwidth=6, height=1) # Text组件索引用"行号.列号"格式,第一行第一列对应"1.0" entry1.insert("1.0","+") entry1.place(x=10, y=120) # 消息输入区 label=Label(root, text="الرسالة", font=10 , fg="white", bg="black") label.place(x = 10, y=360) message_str = StringVar() # 移除Text组件不支持的textvariable参数,补充height参数适配多行消息布局 entry2 = Text(root, width=41, bd=6, font=14, borderwidth=6, height=8) entry2.insert("1.0", "write your message") entry2.place(x=10, y=400) # 时间显示区 label=Label(root, text="وقت الانتظار24/الساعة", font=20 , fg="white", bg="black") label.place(x = 10, y=450) labe4=Label(root, font=20 , fg="white", bg="black") labe4.place(x = 220, y=450) # 本地实时时间刷新功能 def localtime(): t = time.localtime() current_time = time.strftime("%H:%M:%S", t) labe4.config(text="localtime:"+current_time) labe4.after(200, localtime) localtime() # 小时输入框 entry3 = Entry(root, width=20) entry3.insert(0, "15") entry3.place(x=15, y=490) # 分钟输入框 entry4 = Entry(root, width=20) entry4.insert(0, "20") entry4.place(x=150, y=490) # WhatsApp定时发送逻辑 def whatsapp(): # Text组件读取内容需指定起止索引,"1.0"到END为全部内容,strip去掉末尾自动追加的换行 number = entry1.get("1.0", END).strip() message = entry2.get("1.0", END).strip() time1 = int(entry3.get()) time2 = int(entry4.get()) pywhatkit.sendwhatmsg(number, message,time1,time2) send = Button(root, font="30", width=40, text="ارسال" , fg="black", bg="gold" , bd=10, command=whatsapp) send.place(x = 15 , y = 520) root.mainloop()
内容的提问来源于stack exchange,提问作者Hossam Salem
相关产品推荐
相关产品推荐

