前两天看到一篇关于Python使用Tkinter 的博文,写的很好。就拿来研究了一下,改了改。现分享如下:

参考

代码

# coding:utf8
# python2.73 winxp
'''''
天气插件: 使用json接受中气象的本地信息,显示使用tkinter
url http://www.weather.com.cn/data/sk/101221201.html

v0.1
'''
from Tkinter import *
import json
import urllib
import time

def getWeaInfo():
    url = r'http://www.weather.com.cn/data/cityinfo/101221201.html'
    res = urllib.urlopen(url)  # 返回的是个json样式的字符串
    weatherinfo = {}
    jinfo = res.read().decode('utf8')  # jinfo是一个unicode对象,而我们要的是一个json,然后解析
    info = json.loads(jinfo)  # 变成键值对

    if info:
        try:
            weatherinfo['city'] = info['weatherinfo']['city']  # 城市
            weatherinfo['tempH'] = info['weatherinfo']['temp1']  # 高温
            weatherinfo['tempL'] = info['weatherinfo']['temp2']  # 低温
            weatherinfo['weather'] = info['weatherinfo']['weather']  # 天气
            weatherinfo['ptime'] = info['weatherinfo']['ptime']  # 发布时间
        except KeyError, e:
            print 'Do not get the key', e.message
    return weatherinfo

class WeatherFrame:
    '''''
    用于显示主框架
    '''

    def __init__(self):
        self.root = Tk()

        # 一个标题
        self.title = Label(self.root, text=u'天气情况')
        self.title.pack(side=TOP)

        # 四对信息框
        self.fm1 = Frame(self.root)
        self.label_city = Label(self.fm1, text=u'城市')
        self.label_city.pack(side=LEFT, expand=YES)
        self.text_city_e = StringVar()
        self.text_city = Entry(self.fm1, text='', state='readonly', textvariable=self.text_city_e)
        self.text_city.pack(side=LEFT, expand=YES)
        self.fm1.pack(side=TOP)

        self.fm2 = Frame(self.root)
        self.label_temph = Label(self.fm2, text=u'高温')
        self.label_temph.pack(side=LEFT, expand=YES)
        self.text_temph_e = StringVar()
        self.text_temph = Entry(self.fm2, text='', state='readonly', textvariable=self.text_temph_e)
        self.text_temph.pack(side=LEFT, expand=YES)
        self.fm2.pack(side=TOP)

        self.fm3 = Frame(self.root)
        self.label_templ = Label(self.fm3, text=u'低温')
        self.label_templ.pack(side=LEFT, expand=YES)
        self.text_templ_e = StringVar()
        self.text_templ = Entry(self.fm3, text='', state='readonly', textvariable=self.text_templ_e)
        self.text_templ.pack(side=LEFT, expand=YES)
        self.fm3.pack(side=TOP)

        self.fm4 = Frame(self.root)
        self.label_weather = Label(self.fm4, text=u'天气')
        self.label_weather.pack(side=LEFT, expand=YES)
        self.text_weather_e = StringVar()
        self.text_weather = Entry(self.fm4, text='', state='readonly', textvariable=self.text_weather_e)
        self.text_weather.pack(side=LEFT, expand=YES)
        self.fm4.pack(side=TOP)

        # 两个操作按钮
        self.fm5 = Frame(self.root)
        self.button_pull = Button(self.fm5, text=u'获取', command=self.pullWeaInfo)
        self.button_pull.pack(side=LEFT, expand=YES)
        self.button_quit = Button(self.fm5, text=u'退出', command=self.root.quit)
        self.button_quit.pack(side=LEFT, expand=YES)
        self.fm5.pack(side=TOP)

        self.pullWeaInfo()

    def pullWeaInfo(self):
        # 推送天气信息,初始化推送,手动更新
        weainfo = getWeaInfo()
        self.text_city_e.set(weainfo['city'])
        self.text_temph_e.set(weainfo['tempH'])
        self.text_templ_e.set(weainfo['tempL'])
        self.text_weather_e.set(weainfo['weather'])
        print ('lastest updated time is  %s' % time.ctime())

if __name__ == '__main__':
    wf = WeatherFrame()
    mainloop()

效果

我的修改

中国城市代码

城市代码获取

代码

# coding:utf-8
import sys

reload(sys)
sys.setdefaultencoding('utf8')
#    __author__ = '郭 璞'
#    __date__ = '2016/8/26'
#    __Desc__ = 天气预报小案例

from Tkinter import *
import urllib2
import json

def getWeatherInfoByCityCode(citycode):
    url = r'http://www.weather.com.cn/data/cityinfo/'+str(citycode)+'.html'
    data = urllib2.urlopen(url).read().decode('utf8')

    json_info = json.loads(data)
    weatherinfo = {}
    weatherinfo['city'] = json_info['weatherinfo']['city']  # 城市
    weatherinfo['tempH'] = json_info['weatherinfo']['temp2']  # 高温
    weatherinfo['tempL'] = json_info['weatherinfo']['temp1']  # 低温
    weatherinfo['weather'] = json_info['weatherinfo']['weather']  # 天气
    weatherinfo['ptime'] = json_info['weatherinfo']['ptime']  # 发布时间
    return weatherinfo

def show_in_tkinter(ccode):
    tk = Tk()
    citycode = StringVar()
    citycode.set(ccode)
    weatherinfo = getWeatherInfoByCityCode(citycode.get())

    frame1 = Frame(tk)
    Label(frame1,text='输入城市代码').pack(side=LEFT,expand=YES)
    Entry(frame1,textvariable=citycode).pack()
    frame1.pack(side=TOP)

    frame2 = Frame(tk)
    Label(frame2, text='城市名称').pack(side=LEFT, expand=YES)
    cityname = '%s'%weatherinfo['city']
    str_v_cityname = StringVar()
    str_v_cityname.set(cityname)
    Entry(frame2, textvariable=str_v_cityname,state='readonly').pack()
    frame2.pack(side=TOP)

    frame3 = Frame(tk)
    Label(frame3, text='     高温').pack(side=LEFT, expand=YES)
    temp_h = '%s' % weatherinfo['tempH']
    str_v_temp_h = StringVar()
    str_v_temp_h.set(temp_h)
    Entry(frame3, textvariable=str_v_temp_h, state='readonly').pack()
    frame3.pack(side=TOP)

    frame4 = Frame(tk)
    Label(frame4, text='     低温').pack(side=LEFT, expand=YES)
    temp_l = '%s' % weatherinfo['tempL']
    str_v_temp_l = StringVar()
    str_v_temp_l.set(temp_l)
    Entry(frame4, textvariable=str_v_temp_l, state='readonly').pack()
    frame4.pack(side=TOP)

    frame5 = Frame(tk)
    Label(frame5, text='     天气').pack(side=LEFT, expand=YES)
    weather = '%s' % weatherinfo['weather']
    str_v_weather = StringVar()
    str_v_weather.set(weather)
    Entry(frame5, textvariable=str_v_weather, state='readonly').pack()
    frame5.pack(side=TOP)

    frame6 = Frame(tk)
    Label(frame6, text='更新时间').pack(side=LEFT, expand=YES)
    updatetime = '%s' % weatherinfo['ptime']
    str_v_updatetime = StringVar()
    str_v_updatetime.set(updatetime)
    Entry(frame6, textvariable=str_v_updatetime, state='readonly').pack()
    frame6.pack(side=TOP)

    frame7 = Frame(tk)
    btn_pull = Button(frame7,text='获取数据',command=lambda:show_in_tkinter(citycode.get()))
    print citycode.get()
    # btn_pull.bind(citycode.get(),update_weather)
    btn_pull.pack(side=LEFT, expand=YES)
    btn_quit = Button(frame7,text='退出',command=tk.quit).pack(side=LEFT, expand=YES)
    frame7.pack(side=TOP)

    tk.mainloop()

if __name__=="__main__":
    show_in_tkinter(101180308)

测试结果

不足之处

本来设计的是可以输入城市代码,来实时的获取对应的天气信息,并更新到界面上的,但是不知道为什么系统会默认新开一个Tkinter的界面,导致刷新失败!

有时间再来更新本文,打个时间戳:2016年8月26日22:50:14

Python Tkinter小试的更多相关文章

  1. Python Tkinter基础控件入门实例

    分享一个Python Tkinter基础控件用法的入门例子,包括窗口的显示.显示内置图片.弹出窗口.菜单等. 例子,Python Tkinter基础控件的用法 # -*- coding: utf-8 ...

  2. Python Tkinter 学习成果:点歌软件music

    笔者工作业余时间也没什么爱好,社交圈子也小,主要娱乐就是背着自己带电瓶的卖唱音响到住地附近找个人多的位置唱唱KtV. 硬件上点歌就用笔记本电脑,歌曲都是网上下载的mkv格式的含有两个音轨的视频.因此点 ...

  3. Python Tkinter Entry(文本框)

    Python学习记录--关于Tkinter Entry(文本框)的选项.方法说明,以及一些示例. 属性(Options) background(bg) borderwidth(bd) cursor e ...

  4. python tkinter Listbox用法

    python tkinter组件的Listbox的用法,见下面代码的演示: from tkinter import * root=Tk() v=StringVar() #Listbox与变量绑定' l ...

  5. python Tkinter之Button

    Button小部件是一个标准的Tkinter的部件,用于实现各种按钮.按钮可以包含文本或图像,您可以调用Python函数或方法用于每个按钮. Tkinter的按钮被按下时,会自动调用该函数或方法. 该 ...

  6. python gui tkinter快速入门教程 | python tkinter tutorial

    本文首发于个人博客https://kezunlin.me/post/d5c57f56/,欢迎阅读最新内容! python tkinter tutorial Guide main ui messageb ...

  7. Python tkinter模块弹出窗口及传值回到主窗口操作详解

    这篇文章主要介绍了Python tkinter模块弹出窗口及传值回到主窗口操作,结合实例形式分析了Python使用tkinter模块实现的弹出窗口及参数传递相关操作技巧,需要的朋友可以参考下 本文实例 ...

  8. Python Tkinter 文本框(Entry)

    Python Tkinter 文本框用来让用户输入一行文本字符串. 你如果需要输入多行文本,可以使用 Text 组件. 你如果需要显示一行或多行文本且不允许用户修改,你可以使用 Label 组件. 语 ...

  9. Python Tkinter 窗口创建与布局

    做界面,首先需要创建一个窗口,Python Tkinter创建窗口很简单:(注意,Tkinter的包名因Python的版本不同存在差异,有两种:Tkinter和tkinter,读者若发现程序不能运行, ...

随机推荐

  1. [LeetCode] Find Duplicate Subtrees 寻找重复树

    Given a binary tree, return all duplicate subtrees. For each kind of duplicate subtrees, you only ne ...

  2. [LeetCode] Zuma Game 祖玛游戏

    Think about Zuma Game. You have a row of balls on the table, colored red(R), yellow(Y), blue(B), gre ...

  3. dropzone.js使用实践

    官网地址:http://www.dropzonejs.com/ 一,它是什么: DropzoneJS is an open source library that provides drag'n'dr ...

  4. php一句话反弹bash shell

    来源:https://www.leavesongs.com/PHP/backshell-via-php.html 用到了,记录一下 $sock = fsockopen($ip, $port); $de ...

  5. LOJ #6031 字符串

    Description Solution 当 \(k\) 值较小时,发现询问串比较多,串长比较小 然后对 \(Q\) 个询问区间离线跑莫队,一次考虑每一个区间的贡献 假设一个区间 \([i,j]\) ...

  6. hdu 5340 (manacher)

    Sample Input 2 abc abaadada   Sample Output Yes No 判断是否能成为3个非空回文子串 manacher算法求出个点回文长度,在找出第一个和最后一个保存下 ...

  7. hdu 5428

    题意:一个数是这n个数的乘,找出它一个不是素数的最小因子 求出所有数的所有质因子中最小的两个,相乘就是答案.如果所有数字的质因子个数不到两个,那么就是无解. #include<iostream& ...

  8. bzoj 4448: [Scoi2015]情报传递

    Description 奈特公司是一个巨大的情报公司,它有着庞大的情报网络.情报网络中共有n名情报员.每名情报员口J-能有 若T名(可能没有)下线,除1名大头日外其余n-1名情报员有且仅有1名上线.奈 ...

  9. [BZOJ]1042 硬币购物(HAOI2008)

    失踪OJ回归. 小C通过这道题mark一下容斥一类的问题. Description 硬币购物一共有4种硬币.面值分别为c1,c2,c3,c4.某人去商店买东西,去了tot次.每次带di枚ci硬币,买s ...

  10. 某些情况下调用函数为什么要在函数名前加“(void)”

    我们知道,在定义函数时,加在函数名前的"void"表示该函数没有返回值.但在调用时,在函数名前加"(void)"的作用又是什么呢? 最明显的一点就是表示程序并不 ...