以下是问题:如何定义未调用窗口小部件功能时发生的事件?
或者,哇我可以定期更新tkinter中的stringVar(例如,更新时钟上的时间)?特别是,变量是基于从网络上刮下的数据而改变的,我正在看的一些应用程序是;通过网络报告的股票代码,天气指标,家庭安全系统和监控传感器。
到目前为止,我唯一能想到的是创建一个函数,它的最后一个调用会触发一个再次调用该函数的事件。在这种情况下,我无法找到一个看起来合适的标准事件,因此我必须定义一个,但我还不太熟悉这样做,而且,我想避免这种情况,如果有一种更简单的方法。
我一直用来研究这个项目的来源, www.automatetheboringstuff.com ...谢谢Al Sweigart,这是一个很好的资源。 " Tkinter GUI应用程序开发蓝图"作者:Bhaskar Chaudhary " Tkinter GUI开发热点:通过处理10个真实应用程序,开发令人兴奋和精通Python和Tkinter的GUI应用程序"作者:Chaudhary,Bhaskar
这是我到目前为止提出的代码。
from tkinter import *
import requests
import bs4
root = Tk()
svar1 = StringVar() #string variable to display data in the Entry Widget.
button1 = Button(root, text="What time is it?") #Button to be clicked to call a function, I don't want a button in the final product.
label1 = Label(root, text="Time From Google") #this snippet pulls the current time from google.
entry2 = Entry(root, textvariable = svar2)
def gettimefromGoogle():
site1 = requests.get("the url for a google search of 'what time is it right now?'")
if not site1.status_code ==200: # make sure site loaded, if not, did you replace the code in the previous line?
print('Time to play dino game!! ;)')
return
site1soup = bs4.BeautifulSoup(site1.text)
elems = site1soup.select('div')
time = elems[29].getText() #when I created the program, element 29 seemed to have the right data
time = time.replace(" ('your time zone') Time in 'your city', 'your state'",'') #for code to work, you'll have to replace the '' with your own info.
svar1.set(time)
site1= 1 #reassign the namespace, just to save space since Beautiful Soup objects can be quite large.
entry1 = Entry(root, textvariable = svar1, command=gettimefromGoogle)
button1.bind("<Button-1>",gettimefromGoogle) #this is where it would be nice to have an action that calls the function at a periodic interval, say every 10 seconds or so.
button1.grid(row=3,column=2) #currently, the button displays the time when clicked.
label1.grid(row=1,column=2)
entry1.grid(row=2,column=2, columnspan=4)
root.mainloop()`