Python ] }) 已解析=美化组(分别为文本“lxml”,仅解析=筛选数据) idx=combo.current()#获取组合框选择的索引 尝试: dst_td_tags=parsed.find('td',string=self.query_list[idx])。find_next_同胞() 除: 导入回溯 打印(traceback.format_exc()) raise Name ERROR(f'===必须与网页上的数据匹配。名称:{self.query_list[idx]}===')#文字格式Py3.6↑ dst_列表=[dst_td_标记中td的td.text] 价格、变更、变更百分比、更新时间=dst列表 change_percent=change_percent.split('%')[0]#只要可以使用str.replace(),就应该使用它而不是re.sub。 更新时间=更新时间。替换('\n\t','') 更改百分比=更改百分比 更新时间=更新时间 self.\u intvar\u price.set(价格) self.\u strvar\u change.set(更改) self.\u strvar\u change\u percent.set(更改百分比) self.\u strvar\u update\u time.set(更新时间) 如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu': obj=CQueryOil([“WTI原油”、“布伦特原油”、“火星美国”、“欧佩克篮子”、“加拿大原油指数”))#必须与网页上的数据相匹配 obj.run()
正确的方法是使用Python ] }) 已解析=美化组(分别为文本“lxml”,仅解析=筛选数据) idx=combo.current()#获取组合框选择的索引 尝试: dst_td_tags=parsed.find('td',string=self.query_list[idx])。find_next_同胞() 除: 导入回溯 打印(traceback.format_exc()) raise Name ERROR(f'===必须与网页上的数据匹配。名称:{self.query_list[idx]}===')#文字格式Py3.6↑ dst_列表=[dst_td_标记中td的td.text] 价格、变更、变更百分比、更新时间=dst列表 change_percent=change_percent.split('%')[0]#只要可以使用str.replace(),就应该使用它而不是re.sub。 更新时间=更新时间。替换('\n\t','') 更改百分比=更改百分比 更新时间=更新时间 self.\u intvar\u price.set(价格) self.\u strvar\u change.set(更改) self.\u strvar\u change\u percent.set(更改百分比) self.\u strvar\u update\u time.set(更新时间) 如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu': obj=CQueryOil([“WTI原油”、“布伦特原油”、“火星美国”、“欧佩克篮子”、“加拿大原油指数”))#必须与网页上的数据相匹配 obj.run(),python,tkinter,Python,Tkinter,正确的方法是使用StringVar设置标签的初始值,然后只需调用要更新的StringVar实例的.set()方法 例如: price_str = StringVar() prica_label = Label(root, textvariable=price_str).pack() price_str.set("new price") import tkinter as tk counter = 0 def counter_label(label): def count():
StringVar
设置标签的初始值,然后只需调用要更新的StringVar
实例的.set()
方法
例如:
price_str = StringVar()
prica_label = Label(root, textvariable=price_str).pack()
price_str.set("new price")
import tkinter as tk
counter = 0
def counter_label(label):
def count():
global counter
counter += 1
label.config(text=str(counter))
label.after(1000, count)
count()
root = tk.Tk()
root.title("Counting Seconds")
label = tk.Label(root, fg="green")
label.pack()
counter_label(label)
button = tk.Button(root, text='Stop', width=25, command=root.destroy)
button.pack()
root.mainloop()
from tkinter import *
from tkinter.ttk import *
import requests
from tkinter.ttk import Combobox
from bs4 import BeautifulSoup, SoupStrainer
# import re # As long as you can make do with str.replace(), you should use it instead of re.sub.
class CQueryOil(Tk):
def __init__(self, query_country: list):
super().__init__() # init Tk
self.__url = 'http://oilprice.com/oil-price-charts/45'
self._query_country = query_country
self._intvar_price = IntVar()
self._strvar_change = StringVar(value='')
self._strvar_change_percent = StringVar(value='')
self._strvar_update_time = StringVar(value='')
self.init_ui()
@property
def url(self):
return self.__url
@property
def query_list(self):
return self._query_country
def run(self):
self.mainloop()
def init_ui(self) -> None:
self.geometry("225x125")
self.resizable(0, 0)
self.title("Global Oil Price GUI")
[self.grid_columnconfigure(col, weight=1) for col in (1, 2)]
n_padx = 5
Label(self, text="Futures & Indexes", justify=LEFT).grid(row=0, column=0, padx=n_padx, sticky='w')
combo = Combobox(self, values=self.query_list, width=17)
combo.grid(row=1, column=0, padx=n_padx, columnspan=2, sticky='w')
combo.bind("<<ComboboxSelected>>", lambda event: self.update(event, combo=combo))
for cur_row, label_name in enumerate(['Price (USD):', 'Change:', 'Change Percent:', 'Last Updated:']):
Label(self, text=label_name, width=14).grid(row=2 + cur_row, column=0, padx=n_padx, sticky='e')
Label(self, textvariable=self._intvar_price).grid(row=2, column=1, sticky='w')
Label(self, textvariable=self._strvar_change).grid(row=3, column=1, sticky='w')
Label(self, textvariable=self._strvar_change_percent).grid(row=4, column=1, sticky='w')
Label(self, textvariable=self._strvar_update_time).grid(row=5, column=1, sticky='w')
def update(self, event, combo) -> None:
resp = requests.get(self.url)
if resp.status_code != 200:
return
filter_data = SoupStrainer('tr', attrs={'class': ['stripe show_graph', 'stripe show_graph update_on_load']
# 'data-id': ['45', '46', '50', '29', '68']
})
parsed = BeautifulSoup(resp.text, 'lxml', parse_only=filter_data)
idx = combo.current() # Get index of combobox selection
try:
dst_td_tags = parsed.find('td', string=self.query_list[idx]).find_next_siblings()
except:
import traceback
print(traceback.format_exc())
raise NameError(f'====Must match the data on the web page. Name:{self.query_list[idx]}=====') # literal format Py3.6↑
dst_list = [td.text for td in dst_td_tags]
price, change, change_percent, update_time = dst_list
change_percent = change_percent.split('%')[0] # As long as you can make do with str.replace(), you should use it instead of re.sub.
update_time = update_time.replace('\n\t', ' ')
change_percent = change_percent
update_time = update_time
self._intvar_price.set(price)
self._strvar_change.set(change)
self._strvar_change_percent.set(change_percent)
self._strvar_update_time.set(update_time)
if __name__ == '__main__':
obj = CQueryOil(["WTI Crude", "Brent Crude", "Mars US", "Opec Basket", "Canadian Crude Index"]) # Must match the data on the web page
obj.run()
price_str = StringVar()
prica_label = Label(root, textvariable=price_str).pack()
price_str.set("new price")