Python Tkinter 删除函数中的条目

我正在尝试制作一个应用程序来显示不同时区的时间。如果条目不在 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()


忽然笑
浏览 60回答 1
1回答

开心每一天1111

这是我解决这个问题的方法,可能还有其他方法。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()那么它将导致该条目每秒被删除。当您也想搜索更多城市时,这很有效。
打开App,查看更多内容
随时随地看视频慕课网APP