[英]Python Tkinter deleting entry in function
我正在尝试制作一个应用程序来显示不同时区的时间。 如果条目不在 pytz.all_timezones 中,并且用户输入了不包含逗号的内容,我已经尝试使消息框出错。 该应用程序似乎可以正常工作,直到我开始删除该条目,并且它出现了一个我不想要的消息框。 另外,如何让时间不受条目更改的影响,直到我再次按下搜索按钮,因为一旦我开始删除条目,时间就会停止更新。
谢谢
import tkinter as tk
from tkinter import *
from tkinter import messagebox
from datetime import datetime
import pytz
import time
root=tk.Tk()
root.title('Time app')
def times():
a = entry_1.get()
try:
b = a.index(',')
c = a[b + 2:] + '/' + a[:b]
if c in pytz.all_timezones:
home = pytz.timezone(c)
local_time = datetime.now(home)
current_time = local_time.strftime('%H:%M:%S')
place_lbl = Label(root, text=a, bg='grey', width=15, font=('bold', 25))
place_lbl.place(relx=0.33, rely=0.4)
time_lbl = Label(root, text=current_time, bg='grey', font=('bold', 30))
time_lbl.place(relx=0.41, rely=0.5)
time_lbl.after(200,times)
else:
messagebox.showerror('Error',"Cannot find '{}'. Please enter in form city, continent (e.g. London, Europe).".format(a))
except:
messagebox.showerror('Error',"Cannot find '{}'. Please enter in form city, continent (e.g. London, Europe).".format(a))
entry_1.delete(first=0, last=20)
canvas=tk.Canvas(root,height=400,width=700,bg='grey')
canvas.grid()
header_lbl=Label(root,text='Enter a city: ',bg='grey',fg='black',font=('bold',25))
header_lbl.place(relx=0.41,rely=0.1)
entry_1=Entry(root)
entry_1.place(relx=0.37,rely=0.2)
search_btn=Button(root,text='Search',command=times)
search_btn.place(relx=0.47,rely=0.3)
root.mainloop()
这是我解决此问题的方法,也可能有其他方法。
def value():
global a
a = entry_1.get()
def times():
try:
b = a.index(',')
c = a[b + 2:] + '/' + a[:b]
if c in pytz.all_timezones:
home = pytz.timezone(c)
local_time = datetime.now(home)
current_time = local_time.strftime('%H:%M:%S')
place_lbl = Label(root, text=a, bg='grey', width=15, font=('bold', 25))
place_lbl.place(relx=0.33, rely=0.4)
time_lbl = Label(root, text=current_time, bg='grey', font=('bold', 30))
time_lbl.place(relx=0.41, rely=0.5)
time_lbl.after(1000,times)
else:
messagebox.showerror('Error',"Cannot find '{}'. Please enter in form city, continent (e.g. London, Europe).".format(a))
except:
messagebox.showerror('Error',"Cannot find '{}'. Please enter in form city, continent (e.g. London, Europe).".format(a))
确保将您的按钮更改为:
search_btn = Button(root,text='Search',command=lambda:[value(),times(),entry_1.delete(0, END)])
问题是你使用after()
但是一旦代码运行,输入框是空的,然后你将使用框中删除的值。 所以我最初将值传递给另一个函数,以便将其存储在那里。
使用按钮命令,我调用了三个函数,第一个是value()
,它将具有来自条目小部件的值,然后是times()
,第二个是删除条目小部件。 如果您在times()
包含删除内容,则会导致该条目每秒被删除。
当您也想搜索更多城市时,这也适用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.