简体   繁体   English

Tkinter 消息框运行两次

[英]Tkinter messagebox running twice

I'm making an app which finds the time and Google description of the user's input, and if the input is invalid an error messagebox pops up.我正在制作一个应用程序,它可以找到用户输入的时间和 Google 描述,如果输入无效,则会弹出一个错误消息框。 However, if I enter a valid input and run it, and then enter an invalid input and try to run it, the messagebox will open up again after I close it.但是,如果我输入一个有效的输入并运行它,然后输入一个无效的输入并尝试运行它,则消息框将在我关闭后再次打开。 Otherwise it works fine, and I'm not sure what the problem is.否则它工作正常,我不确定问题是什么。 Any help would be great, thanks.任何帮助都会很棒,谢谢。

import tkinter as tk
from tkinter import *
from tkinter import messagebox
from datetime import datetime
import pytz
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait


root=tk.Tk()
root.title('Time app')

p_names=['London, Europe','Paris, Europe','Stockholm, Europe','Tokyo, Asia','Arizona, US','Pacific, US','Samoa, Pacific','Galapagos, Pacific','General, Mexico','Mauritius, Indian','Johannesburg, Africa','Barbados, America','Detroit, America','Addis Ababa, Africa','El Salvador, America','Bangkok, Asia']

def place_names():
    p_names.sort()
    li=''
    for pl in p_names:
        li+=pl
        li+='\n'
    return li+'\n'+'+ more'


def value():
    global a
    a = entry_1.get()
    try:
        a.index(',')
        if a.index(' ')<a.index(','):
            a=a.replace(' ','_')
    except:
        a=a
    
    return a


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')
    
            d= a
    
            try:
                e=d.index('_')
                if e<d.index(','):
                    d=d.replace('_',' ')
            except:
                d=a
    
            place_lbl = Label(root, text=d, bg='grey',width=15, font=('bold', 25))
            place_lbl.place(relx=0.33, rely=0.45)
    
            time_lbl = Label(root, text=current_time, bg='grey', font=('bold', 30))
            time_lbl.place(relx=0.41, rely=0.6)
            time_lbl.after(1000,times)
        else:
            messagebox.showerror('Error',"Cannot find '{}'. Please enter in form city, continent (e.g. Arizona, US) or try another location.".format(a))
    except:
        messagebox.showerror('Error',"I Cannot find '{}'. Please enter in form city, continent (e.g. Arizona, US) or try another location.".format(a))
    
    return


def scraped():

    try:
        b = a.index(',')
        c = a[b + 2:] + '/' + a[:b]
    
        if c in pytz.all_timezones:
            PATH = '/Users/BenMcNally/Desktop/chromedriver'
            option = webdriver.ChromeOptions()
            option.add_argument('headless')
            driver = webdriver.Chrome(PATH, options=option)
            driver.implicitly_wait(10)
            driver.get('https://www.google.com/webhp?hl=en&sa=X&ved=0ahUKEwjhj7PUqL_sAhXcURUIHZfmA4oQPAgI')
    
            try:
                search = driver.find_element_by_xpath('//*[@id="tsf"]/div[2]/div[1]/div[1]/div/div[2]/input')
                search.send_keys(a)
                search.send_keys(Keys.RETURN)
    
                desc = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="kp-wp-tab-overview"]/div[1]/div/div/div/div[1]')))
    
                side_info_lbl.config(text=desc.text)
            except:
                side_info_lbl.update_idletasks()
                side_info_lbl.config(text='No description available')
    
    
            driver.quit()
    except:
        return


canvas=tk.Canvas(root,height=400,width=700,bg='grey')
canvas.grid()

header_lbl=Label(root,text='Enter a location: ',bg='grey',fg='black',font=('bold',25))
header_lbl.place(relx=0.38,rely=0.1)

entry_1=Entry(root)
entry_1.place(relx=0.37,rely=0.2)

search_btn = Button(root,text='Search',command=lambda:[value(),times(),entry_1.delete(0, 
END),scraped()])
search_btn.place(relx=0.47,rely=0.3)

show_lbl=Label(root,text='Locations',bg='grey',fg='black',font=('bold',20))
show_lbl.place(relx=0.12,rely=0.1)

side_list_lbl=Label(root,text=place_names(),bg='grey',fg='black')
side_list_lbl.place(relx=0.1,rely=0.2)

side_info_lbl = Label(root, text='', wraplength=200, bg='grey', 
fg='black',height=20,width=22)
side_info_lbl.place(relx=0.68, rely=0.1)


root.mainloop()

That's because you called .after firstly.And when you enter a incorrect area, Both of them will raise exception.那是因为你首先调用了.after当你输入一个错误的区域时,它们都会引发异常。

So the solution is to stop .after method(use .after_cancel() ) each time you pressed the button:因此,解决办法是停止.after方法(使用.after_cancel()每次按下按钮时:

import tkinter as tk
from tkinter import *
from tkinter import messagebox
from datetime import datetime
import pytz
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait


root=tk.Tk()
root.title('Time app')

p_names=['London, Europe','Paris, Europe','Stockholm, Europe','Tokyo, Asia','Arizona, US','Pacific, US','Samoa, Pacific','Galapagos, Pacific','General, Mexico','Mauritius, Indian','Johannesburg, Africa','Barbados, America','Detroit, America','Addis Ababa, Africa','El Salvador, America','Bangkok, Asia']

def place_names():
    p_names.sort()
    li=''
    for pl in p_names:
        li+=pl
        li+='\n'
    return li+'\n'+'+ more'


def value():
    global a
    if root.get_time: # if you have run it. root.get_time wouldn't be None
        root.after_cancel(root.get_time) # cancel it
    a = entry_1.get()
    if root.get_time:
        root.after_cancel(root.get_time)
    try:
        a.index(',')
        if a.index(' ')<a.index(','):
            a=a.replace(' ','_')
    except:
        a=a
    return a


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')

            d= a

            try:
                e=d.index('_')
                if e<d.index(','):
                    d=d.replace('_',' ')
            except:
                d=a

            place_lbl = Label(root, text=d, bg='grey',width=15, font=('bold', 25))
            place_lbl.place(relx=0.33, rely=0.45)

            time_lbl = Label(root, text=current_time, bg='grey', font=('bold', 30))
            time_lbl.place(relx=0.41, rely=0.6)
            root.get_time = root.after(1000, times)
        else:
            messagebox.showerror('Error',"Cannot find '{}'. Please enter in form city, continent (e.g. Arizona, US) or try another location.".format(a))
    except:
        messagebox.showerror('Error',"I Cannot find '{}'. Please enter in form city, continent (e.g. Arizona, US) or try another location.".format(a))

    return


def scraped():
    try:
        b = a.index(',')
        c = a[b + 2:] + '/' + a[:b]

        if c in pytz.all_timezones:
            PATH = '/Users/BenMcNally/Desktop/chromedriver'
            option = webdriver.ChromeOptions()
            option.add_argument('headless')
            driver = webdriver.Chrome(PATH, options=option)
            driver.implicitly_wait(10)
            driver.get('https://www.google.com/webhp?hl=en&sa=X&ved=0ahUKEwjhj7PUqL_sAhXcURUIHZfmA4oQPAgI')

            try:
                search = driver.find_element_by_xpath('//*[@id="tsf"]/div[2]/div[1]/div[1]/div/div[2]/input')
                search.send_keys(a)
                search.send_keys(Keys.RETURN)

                desc = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="kp-wp-tab-overview"]/div[1]/div/div/div/div[1]')))

                side_info_lbl.config(text=desc.text)
            except:
                side_info_lbl.update_idletasks()
                side_info_lbl.config(text='No description available')


            driver.quit()
    except:
        return


canvas=tk.Canvas(root,height=400,width=700,bg='grey')
canvas.grid()

header_lbl=Label(root,text='Enter a location: ',bg='grey',fg='black',font=('bold',25))
header_lbl.place(relx=0.38,rely=0.1)

entry_1=Entry(root)
entry_1.place(relx=0.37,rely=0.2)

root.get_time = None # init value
search_btn = Button(root,text='Search',command=lambda: [value(),times(),entry_1.delete(0, END),scraped()])
search_btn.place(relx=0.47,rely=0.3)

show_lbl=Label(root,text='Locations',bg='grey',fg='black',font=('bold',20))
show_lbl.place(relx=0.12,rely=0.1)

side_list_lbl=Label(root,text=place_names(),bg='grey',fg='black')
side_list_lbl.place(relx=0.1,rely=0.2)

side_info_lbl = Label(root, text='', wraplength=200, bg='grey',
fg='black',height=20,width=22)
side_info_lbl.place(relx=0.68, rely=0.1)


root.mainloop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM