Python學習,給自己的代碼做個合集,定制自己的桌面軟件!


Python學習,給自己的代碼做個合集,定制自己的桌面軟件!

 

在學習Python的過程中,經常會寫很多的練手的腳本,那么有沒有想過,寫到一起呢?當然了,方法有很多,比如寫到web網頁中,做各種跳轉、寫到微信中,各種回復關鍵字調用,還有今天和大家分享的GUI圖形用戶界面!

構建基本框架

Python中有標准庫tkinter,不需要安裝即可使用!可以用來寫簡單的GUI程序,只需要短短幾行代碼就可以了,比如下面這個:

Python學習,給自己的代碼做個合集,定制自己的桌面軟件!

 

具體教程大家可以去自行搜索,這里就不一一細說了,注釋也寫的很清楚!

將自己的其他腳本都寫到GUI程序中

其實可以導入其他腳本中的函數,來達到多個腳本整合的效果,但是那樣又不是很方便,就先放到一起了,慢慢在完善!

首先是將之前的天氣預報寫入(這里有個城市代碼的字典省略了,很長,大家可以去我相關的文章中查找)

def weather():
    '''    天氣預報查詢    '''
    global city_code_list#城市列表
    city = entry.get()#獲取輸入的城市名
    if city in city_code_list:
        city_code = city_code_list[city]
        home_page = 'http://www.weather.com.cn'
        url = home_page + '/weather/' + city_code + '.shtml'
        header = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0'}
        res = requests.get(url, headers=header)
        res.encoding = 'utf-8'
        html = etree.HTML(res.text)
        for i in range(1, 8):
            date = html.xpath('//ul[@class="t clearfix"]/li[{}]/h1/text()'.format(i))[0]
            weather = html.xpath('//ul[@class="t clearfix"]/li[{}]/p[1]/text()'.format(i))[0]
            tem1 = html.xpath('//ul[@class="t clearfix"]/li[{}]/p[@class="tem"]/span/text()'.format(i))
            tem2 = html.xpath('//ul[@class="t clearfix"]/li[{}]/p[@class="tem"]/i/text()'.format(i))
            tem = "".join(tem1) + '/' + "".join(tem2)
            win1 = html.xpath('//ul[@class="t clearfix"]/li[{}]/p[@class="win"]/i/text()'.format(i))
            win2 = html.xpath('//ul[@class="t clearfix"]/li[{}]/p[@class="win"]/em/span[1]/@title'.format(i))
            win = "".join(win1) + "".join(win2)
            text.insert(END,'%s天氣預報查詢'%city)#添加數據
            text.insert(END,'%s %s %s %s'%(date, weather, tem, win))#添加數據
            text.see(END)#文本框向下滾動
            text.update()#更新
    else:
        text.insert(END, '輸錯了吧?')  # 添加數據
        text.see(END)  # 文本框向下滾動
        text.update()  # 更新

 

然后是空氣質量排名

def ranking():
    city = entry.get()
    url = 'http://www.tianqihoubao.com/aqi/aqi_rank.html'
    html = requests.get(url)
    datas = etree.HTML(html.text).xpath('//table[@class="b"]')[0]
    i = 1
    for data in datas:
        trs = data.xpath('./td')
        info = []
        for tr in trs:
            a = tr.xpath('string(.)').split()[0]
            if i % 6 != 0:
                info.append(a)
            elif i == 6:
                text.insert(END, '%s' % (" | ".join(info))) # 第一行
            elif city in info:#判斷需要數據所在行
                text.insert(END, '%s' % ("   |   ".join(info)))  # 添加需要的數據
                text.see(END)  # 文本框向下滾動
                text.update()  # 更新
                info = []
            i += 1

 

最后是空氣指數查詢

 1 def quality():
 2     url = 'http://www.tianqihoubao.com/aqi/'
 3     html = requests.get(url)
 4     html.encoding = 'gbk'
 5     citys = etree.HTML(html.text).xpath('//div[@class="citychk"]/dl/dd/a/text()')
 6     city_urls = etree.HTML(html.text).xpath('//div[@class="citychk"]/dl/dd/a/@href')
 7     dic = {}#構架城市列表
 8     for city, city_url in zip(citys, city_urls):
 9         city = city.replace(" ", "")
10         city_url = 'http://www.tianqihoubao.com/' + city_url
11         dic[city] = city_url
12     city_n = entry.get()
13     if city_n in dic.keys():
14         html_n = requests.get(dic[city_n])
15         html_n.encoding = 'gbk'
16         data = etree.HTML(html_n.text)
17         num = data.xpath('//div[@class="num"]/text()')[0].strip()
18         status = data.xpath('//div[@class="status"]/text()')[0].strip()
19         explain = data.xpath('//div[@class="hd"]/div[@id="content"]/div[@class="txt01"]/h4')[0].xpath('string(.)')
20         surveys = re.findall(r'<td.*?>(.*?)</td>', html_n.text, re.S)
21         sur = re.sub("</b>", "|", ''.join([x.strip().replace("<b>", ' ') for x in surveys[0:9]]))[:-1]
22         sur2 = [x.strip().replace(" ", '') + '|' for x in surveys[9:]]
23         surv = [sur2[i:i + 9] for i in range(0, len(sur2), 9)]
24         text.insert(END,'%s空氣質量查詢' % city_n)  # 添加數據
25         text.insert(END,"%s空氣質量指數: %s" % (city_n, num))  # 添加數據
26         text.insert(END,"%s空氣質量:    %s" %(city_n, status))  # 添加數據
27         text.insert(END,explain)  # 添加數據
28         text.insert(END,sur)  # 添加數據
29         for su in surv:
30             text.insert(END," ".join(su)[:-1])  # 添加數據
31         text.see(END)  # 文本框向下滾動
32         text.update()  # 更新
33     else:
34         text.insert(END, '輸錯了吧?')  # 添加數據
35         text.see(END)  # 文本框向下滾動
36         text.update()  # 更新

 

好了,現在是主函數

 1 if __name__ == '__main__':
 2     root = Tk()
 3     root.title("我的應用匯總")#窗口標題
 4     root.geometry('660x600+600+50')#窗口大小位置 用x鏈接 +后面是位置
 5     label = Label(root,text="<<-----雲飛學編程----Q群542110741----->>",font=('微軟雅黑'))#創建標簽控件
 6     label.grid(row=0,columnspan=3)#網格式布局
 7     text = Listbox(root,font=('微軟雅黑',15),width=55,height=18)#列表框控件,設置組件默認寬高
 8     text.grid(row=2,columnspan=4)#columnspan為組件所跨越的列數
 9     button_tq = Button(root,text="天氣預報查詢",font=('微軟雅黑',8),command=weather)#點擊按鈕
10     button_tq.grid(row=1,column=1)
11     button_kq = Button(root,text="空氣質量查詢",font=('微軟雅黑',8),command=quality)#點擊按鈕
12     button_kq.grid(row=1,column=3)
13     button_pm = Button(root,text="空氣質量排名",font=('微軟雅黑',8),command=ranking)#點擊按鈕
14     button_pm.grid(row=1,column=2)
15     entry = Entry(root,font=('微軟雅黑'))#創建輸入框
16     entry.grid(row=1,column=0)#定位第1行3列
17     root.mainloop()

 

運行效果如下:

Python學習,給自己的代碼做個合集,定制自己的桌面軟件!

上面3個爬蟲,都在以往的文章中發過,大家如果感興趣可以去看看!這里就不詳細注釋了,只是復制過來稍微修改下就用了!

Python學習,給自己的代碼做個合集,定制自己的桌面軟件!

待改進:

1、內容添加,目前就3個爬蟲的內容,慢慢添加更多的感興趣的內容進去,最終形成自己的定制軟件

2、界面的優化,比如滑動條、字體大小、按鈕大小位置等等

3、連接數據庫,目前的內容都是實時抓取網頁內容,連接數據庫會更加的快捷

目前就這么多,想到在繼續吧!剛開始學習GUI,總有不足之處,如果有更好的建議大家可以評論區討論哦!需要源碼的話就私信我吧!

Python學習,給自己的代碼做個合集,定制自己的桌面軟件!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM