python 气温查询

1.气温查询方法
# -*- coding: utf-8 -*- 
import json 
import urllib2 
#打开存储城市编码和城市的文档
f = open('ChinaWeatherCity.txt')
#  定义一个字典,用来存储城市和城市编码
citys = {} 
str_temp = '' 
#进行汉字编码的改变
def changeUncode(variable): 
variable = variable.decode("utf8") 
return variable 

#定义方法用于得到城市的Code
def getCity(cityName): 
for line in f.readlines(): 
line = line.strip('\n') 
lineCity = line.split('=') 
citys[lineCity[1]] = lineCity[0] 
return citys.get(changeUncode(cityName)) 

#定义方法用于得到输入城市的天气情况
def getCityWeather(cityName): 
cityCode = getCity(cityName) 
print cityCode 
try: 
if cityCode: 
#从对应的网页中获取天气信息
url = (' http://www.weather.com.cn/data/cityinfo/%s.html'%cityCode) 
#解析url
content = urllib2.urlopen(url).read() 
#转为json格式
data = json.loads(content) 
#得到data中weatherinfo信息
result = data['weatherinfo'] 
#转化格式
str_temp = ('%s=%s~%s')%(result['weather'],result['temp1'],result['temp2']) 
return str_temp 
else: 
print 'Can not Search City!!' 
return str_temp 
except: 
print 'can not find city' 

2.Python GUI 程序
# -*- coding: utf-8 -*-
from Tkinter import *
from com.allen.weather.W_Method import changeUncode, getCityWeather

#Button点击事件
def  getTemperator():
    entryVar1 = entry1.get()
    print changeUncode(entryVar1)
    weatherVar = getCityWeather(entryVar1)
    print 'start GUI'
    #print weatherVar
    weatherVars = weatherVar.split('=');
    #print weatherVars[0]
    #print weatherVars[1]
    entryVar2.set(str(weatherVars[0]))
    entryVar3.set(str(weatherVars[1]))

#GUI端布局处理  
root = Tk()
# 改变root的大小为150x150
root.geometry('150x150+0+0')
print root.pack_slaves()
# 创建三个Label分别使用不同的fill属性
Label(root,text = 'Please input City Name:').pack(fill = Y)

entryVar1 = StringVar()
entry1 = Entry(root,textvariable=entryVar1)
entry1.pack()

Label(root,text = 'City Weather:').pack(fill = BOTH)

entryVar2=StringVar()
entry2 = Entry(root,textvariable=entryVar2)
entry2.pack()

Label(root,text = 'City Temperator:').pack(fill = X)

entryVar3=StringVar()
entry3 = Entry(root,textvariable=entryVar3)
entry3.pack()

Button(root,text='search weather',command= getTemperator).pack()

print root.pack_slaves()
root.mainloop()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值