作者ww410490 (致命伸卡球)
看板Python
標題[問題] Tkinter + urllib2
時間Wed Oct 14 14:45:21 2015
各位前輩大大好
小弟練習用Tkinter寫GUI
用來查詢各個縣市的溫度
程式碼如下
------------------------------------------------------
import urllib2
from sgmllib import SGMLParser
import Tkinter as tk
class WeatherList(SGMLParser):
is_td=""
name=[]
def start_td(self, attrs):
self.is_td = 1
def end_td(self):
self.is_td=""
def handle_data(self, text):
if self.is_td:
self.name.append(text)
temp = ''
hum = ''
root = tk.Tk()
root.title("CWB")
label_1 = tk.Label(root, text = temp)
label_1.pack()
label_2 = tk.Label(root, text = hum)
label_2.pack()
label_3 = tk.Label(root, text = hum)
label_3.pack()
options = ['Taipei_City','New_Taipei_City','Tainan_City']
var = tk.StringVar()
var.set('Taipei_City')
drop = tk.OptionMenu(root,var,'Taipei_City','New_Taipei_City','Tainan_City')
drop.pack()
def Taipei():
mtext = var.get()
url = '
http://www.cwb.gov.tw/V7/forecast/taiwan/' + mtext + '.htm'
print url
content = urllib2.urlopen(url).read()
Tempreature = WeatherList()
Tempreature.feed(content)
data = []
for i in Tempreature.name:
if '\t' not in i:
data.append( i.decode('utf-8'))
print mtext
print 'temp = ', data[0]
print 'humidity = ', data[2]
label_1.config(text = "temp:" + str(data[0]) , fg = "dark green")
label_2.config(text = "humidity:" + str(data[2]) , fg = "dark green")
label_3.config(text = mtext , fg = "dark green")
button0 = tk.Button(root, text='search', width=25, command= Taipei)
button0.pack()
root.mainloop()
-------------------------------------------------------------------
小弟遇到的問題 在於換縣市查詢時 資料沒有正確回傳
例如查詢Taipei_City 得到的溫度 選擇Tainan 時溫度卻不變
但是我已確定查詢的網址有正確更改
除此之外想不通是哪邊的問題
Any help is appriciated.
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.109.161.132
※ 文章網址: https://www.ptt.cc/bbs/Python/M.1444805123.A.788.html
→ AndCycle: 會變動的文字內容要用 textvariable, 不是 text 10/14 15:32
→ ww410490: 感覺是其他問題耶 因為label3可以顯示變動的網址 10/14 22:48
→ ww410490: 但是變動的網址卻回傳同樣的資料 10/14 22:48
→ ww410490: 自問自答 因為data又繼續存取下個縣市的資料 沒有清空 10/14 22:53
→ ww410490: 總之謝謝A大提點 10/14 22:54