首页
游戏
影视
直播
广播
听书
音乐
图片
更多
看书
微视
主播
统计
友链
留言
关于
论坛
邮件
推荐
我的硬盘
我的搜索
我的记录
我的文件
我的图书
我的笔记
我的书签
我的微博
Search
1
在IC617中进行xa+vcs数模混仿
81 阅读
2
科普:Memory Compiler生成的Register file和SRAM有何区别?
73 阅读
3
virtuoso和empyrean alps模拟仿真和混仿教程
73 阅读
4
后仿中$setup,$hold与$setuphold
44 阅读
5
文档内容搜索哪家强? 15款文件搜索软件横向评测
35 阅读
默认分类
芯片市场
数字电路
芯片后端
模拟电路
芯片验证
原型与样片验证
算法与架构
DFX与量产封装
PC&Server OS设置
移动OS设置
软件方案
新浪备份
有道备份
登录
Search
标签搜索
python
Docker
vscode
linux
systemverilog
vcs
STM32
PyQT
EDA
FPGA
gvim
cadence
Alist
xilinx
UVM
uos
macos
package
MCU
risc-v
bennyhe
累计撰写
378
篇文章
累计收到
31
条评论
首页
栏目
默认分类
芯片市场
数字电路
芯片后端
模拟电路
芯片验证
原型与样片验证
算法与架构
DFX与量产封装
PC&Server OS设置
移动OS设置
软件方案
新浪备份
有道备份
页面
游戏
影视
直播
广播
听书
音乐
图片
看书
微视
主播
统计
友链
留言
关于
论坛
邮件
推荐
我的硬盘
我的搜索
我的记录
我的文件
我的图书
我的笔记
我的书签
我的微博
搜索到
15
篇与
的结果
2025-06-06
Python中 if __name__==详细解析
引言学过Java、C、C++的程序员应该都知道,每次开启一个程序,都必须写一个主函数作为程序的入口,也就是我们常说的main函数。如下所示, main()就是Java中的一个main函数。public class HelloWorld { public static void main(String[] args) { System.out.println("HelloWorld"); } }与Java、C、C++等几种语言不同的是,Python是一种解释型脚本语言,在执行之前不同要将所有代码先编译成中间代码,Python程序运行时是从模块顶行开始,逐行进行翻译执行,所以,最顶层(没有被缩进)的代码都会被执行,所以Python中并不需要一个统一的main()作为程序的入口。在某种意义上讲,“if __name__==’__main__:”也像是一个标志,象征着Java等语言中的程序主入口,告诉其他程序员,代码入口在此——这是“if __name__==’__main__:”这条代码的意义之一。__name__的理解1.1 为什么使用__name__属性?Python解释器在导入模块时,会将模块中没有缩进的代码全部执行一遍(模块就是一个独立的Python文件)。开发人员通常会在模块下方增加一些测试代码,为了避免这些测试代码在模块被导入后执行,可以利用__name__属性。1.2 __name__属性。__name__属性是Python的一个内置属性,记录了一个字符串。若是在当前文件,__name__ 是__main__。在hello文件中打印本文件的__name__属性值,显示的是__main__若是导入的文件,__name__是模块名。test文件导入hello模块,在test文件中打印出hello模块的__name__属性值,显示的是hello模块的模块名。因此__name__ == '__main__' 就表示在当前文件中,可以在if name == '__main__':条件下写入测试代码,如此可以避免测试代码在模块被导入后执行。模块导入我们知道,当我们把模块A中的代码在模块B中进行import A时,只要B模块代码运行到该import语句,模块A的代码会被执行。模块A:# 模块A a = 100 print('你好,我是模块A……') print(a) 模块B: # 模块B from package01 import A b = 200 print('你好,我是模块B……') print(b)运行模块B时,输出结果如下:你好,我是模块A……100你好,我是模块B……200如果在模块A中,我们有部分的代码不想在被导入到B时直接被运行,但在直接运行A时可直接运行,那该怎么做呢?那就可以用到“if __name__==’__main__:”这行代码了,我们队上面用到的A模块代码进行修改:A模块代码修改为:# 模块A a = 100 print('你好,我是模块A……') if __name__=='__main__': print(a)B模块不做修改,直接执行B模块,输出结果如下:你好,我是模块A……你好,我是模块B……200看到了吗,A模块中的a的值就没有再被输出了。所以,当你要导入某个模块,但又不想改模块的部分代码被直接执行,那就可以这一部分代码放在“if __name__=='__main__':”内部。3. “__name__”与“__main__”看到现在也许心中还是疑惑,那么现在我们来说一说“if__name__=='__main__':”的原理。“__name__”是Python的内置变量,用于指代当前模块。我们修改上面用到的A模块和B模块,在模块中分别输出模块的名称:模块A:# 模块A print('你好,我是模块A……') print('模块A中__name__的值:{}'.format(__name__)) print('-------------------------') 模块B: # 模块B from package01 import A print('你好,我是模块B……') print('模块B中__name__的值:{}'.format(__name__))执行A模块时,输出结果:你好,我是模块A……模块A中__name__的值:__main__-------------------------执行B模块时,输出结果:你好,我是模块A……模块A中__name__的值:package01.A-------------------------你好,我是模块B……模块B中__name__的值:__main__发现神奇之处了吗?当哪个模块被直接执行时,该模块“__name__”的值就是“__main__”,当被导入另一模块时,“__name__”的值就是模块的真实名称。用一个类比来解释一下:记得小时候要轮流打算教室,轮到自己的时候(模块被直接执行的时候),我们会说今天是“我”(__main__)值日,称呼其他人时,我们就会直接喊他们的名字。所以,“__main__”就相当于当事人,或者说第一人称的“我”。所以,当运行“if __name__=='__main__':”语句时,如果当前模块时被直接执行,__name__的值就是__main__,条件判断的结果为True,“if __name__=='__main__':”下面的代码块就会被执行。1参考.^Python中“if __name__=='__main__':”理解与总结 https://www.cnblogs.com/chenhuabin/p/10118199.html.^if name == '__main__': https://www.cnblogs.com/wanao/p/13098783.html
2025年06月06日
0 阅读
0 评论
0 点赞
2025-06-06
VSCode搭建Python开发环境
文章所需的部署环境为Windows10 64位.这篇文章将演示如何搭建一个VSCode编写Python代码的环境。第一步. 安装Python环境(如果已经安装过的可以略过)下载地址:https://www.python.org/downloads/www.python.org/downloads/目前Python最新版本是3.8.5, 但是该版本还处于BUGFIX阶段,所以我们使用稳定的最新版本3.7.8。python2.7 已经在2020-01-01停止维护,如果还在使用Python2的要及时更新哦点击Download后,我们在新页面选择64位安装程序如果下载速度慢的话可以使用代理下载下来打开后,根据图示安装下一步.Documentation:python文档,建议勾上.pip: python安装其他库的工具,必勾.tcl/tk and IDLE: 安装tkinter库和IDLE开发环境, IDLE就是个编辑器,tkinter以后也可以装,这里不推荐勾选.Python test suite:Python标准库测试测试套装,不是必须下一步安装路径自行调整,其余按图示即可。安装成功测试是否有效,win+r 输入cmd 打开控制台,输入python -V,输出了安装的python版本即成功!如果没有输出或者出错,可能是安装时没有勾选添加python安装路径到环境变量,百度一下如何添加即可。VSCode配置Python开发环境接下来就是配置VSCode了,首先打开VSCode, 搜索插件Python并安装。或者直接打开某个.py文件,VSCode右下角将会自动提示你安装。安装完毕后,VSCode应该会出现这个提示需要你选择一个Python的解析器,点击Select Python Interpreter不出意外的话,你已经将Python路径添加到环境变量,于是VSCode可以自动识别到,图中即是你安装的Python解析器的位置了,选择即可。如果VSCode没有提示你选择,那你可以使用ctrl+shift+p, 输入Python Select Python Interpreter 即可。这一步做完后,VSCode可能还会出现这个提示这是VSCode需要你选择一个代码检查插件,你可以直接点击Install来安装pylint,也可以点击Select Linter选择其他的代码检查插件。这里我选择点击Select Linter。或者直接在setting 中输入interpret, 填写pythona安装后的路径VSCode的Python插件默认是使用pylint作为代码检查插件,我更习惯使用pycodestyle。选择后VSCode应该会提示你该插件未安装,点击Install安装即可。python会调用pip去安装,如下图所示即是安装成功了。黄字WARNING是提示pip版本可更新,无大碍。到这里,你已经可以使用VSCode编写python代码了,来试试看!右键可以点击出许多Python插件提供的功能,试试运行该python文件于终端。或者在终端输入 python hello.py 来运行hello.py文件。或者在python文件点击右键,选择“Run Python File in Terminal”成功输出( ̄︶ ̄*))。可以看到Python插件还提供了很多的功能, 比如选中函数后跳转到其实现。
2025年06月06日
1 阅读
0 评论
0 点赞
2025-05-29
python pandas excel操作
1 获取一个excel文档的所有的sheet方法一:xls = pd.ExcelFile(file_name) sheets = xls.sheet_names num_sheets = len(sheets) print("Excel file contains", num_sheets, "sheets.") print(sheets)打印接轨:Excel file contains 2 sheets.['history', 'test_feature']方法二:sheet=pd.read_excel(file_name,sheet_name=None) print(list(sheet.keys())) for j in sheet.keys(): print(j) 打印结果:['history', 'test_feature']historytest_feature2 读取 excel 表格之读取指定的子表 sheetpandas读取excel使用 read_excel() 函数import pandas as pd df = pd.read_excel('goods_base.xlsx') . sheet_name 参数, 指定读取 sheet 子表 # 单个sheet df = pd.read_excel('sheet_name.xlsx', sheet_name=2) df = pd.read_excel('sheet_name.xlsx', sheet_name='3月') # 多个sheet, 返回字典 df_dict = pd.read_excel('sheet_name.xlsx', sheet_name=[1, '3月']) # 全部sheet, 返回字典 df_dict = pd.read_excel('sheet_name.xlsx', sheet_name=None 3 pandas逐个遍历sheetimport pandas as pd f = pd.ExcelFile('./data.xlsx') for i in f.sheet_names: d = pd.read_excel('./data.xlsx', sheetname=i) print(d)4 读最大的取行列数 import pandas as pd df = pd.read_excel('C:/Users/enuit/Desktop/data_test.xlsx') # 行数 (不包含表头,且一下均如此) print(len(df.index.values)) # 行索引 print(df.index.values) # 列数 print(len(df.columns.values)) # 列索引 print(df.columns.values)结果:5 读取指定行的单元格内容excel 原始的内容比如excel 读出的内容design 的内容df = pd.read_excel(file_name, sheet_name="history") print(df.loc[1,"demo"]) #或者 print(df.iloc[1,1])都是返回designer这个内容。6根据条件筛选单元格# C:\Users\lenovo\Desktop\总结\Python # 读取 Excel 文件并进行筛选 import pandas as pd # 设置列对齐 pd.set_option("display.unicode.ambiguous_as_wide",True) pd.set_option("display.unicode.east_asian_width",True) # 读取工号姓名时段交易额,使用默认索引 dataframe = pd.read_excel(r'C:\Users\lenovo\Desktop\总结\Python\超市营业额.xlsx',usecols = ['工号','姓名','时段','交易额']) # 打印前十行数据 dataframe[:10] 工号 姓名 时段 交易额 0 1001 张三 9:00-14:00 2000 1 1002 李四 14:00-21:00 1800 2 1003 王五 9:00-14:00 800 3 1004 赵六 14:00-21:00 1100 4 1005 周七 9:00-14:00 600 5 1006 钱八 14:00-21:00 700 6 1006 钱八 9:00-14:00 850 7 1001 张三 14:00-21:00 600 8 1001 张三 9:00-14:00 1300 9 1002 李四 14:00-21:00 1500 ''' # 跳过 1 2 4 行,以第一列姓名为索引 dataframe2 = pd.read_excel(r'C:\Users\lenovo\Desktop\总结\Python\超市营业额.xlsx', skiprows = [1,2,4], index_col = 1) '''注:张三李四赵六的第一条数据跳过 工号 日期 时段 交易额 柜台 姓名 王五 1003 20190301 9:00-14:00 800 食品 周七 1005 20190301 9:00-14:00 600 日用品 钱八 1006 20190301 14:00-21:00 700 日用品 钱八 1006 20190301 9:00-14:00 850 蔬菜水果 张三 1001 20190302 14:00-21:00 600 蔬菜水果 ''' # 筛选符合特定条件的数据 # 读取超市营业额数据 dataframe = pd.read_excel(r'C:\Users\lenovo\Desktop\总结\Python\超市营业额.xlsx') # 查看 5 到 10 的数据 dataframe[5:11] ''' 工号 姓名 日期 时段 交易额 柜台 5 1006 钱八 20190301 14:00-21:00 700 日用品 6 1006 钱八 20190301 9:00-14:00 850 蔬菜水果 7 1001 张三 20190302 14:00-21:00 600 蔬菜水果 8 1001 张三 20190302 9:00-14:00 1300 化妆品 9 1002 李四 20190302 14:00-21:00 1500 化妆品 10 1003 王五 20190302 9:00-14:00 1000 食品 ''' # 查看第六行的数据 dataframe.iloc[5] ''' 工号 1006 姓名 钱八 时段 14:00-21:00 交易额 700 Name: 5, dtype: object ''' dataframe[:5] ''' 工号 姓名 时段 交易额 0 1001 张三 9:00-14:00 2000 1 1002 李四 14:00-21:00 1800 2 1003 王五 9:00-14:00 800 3 1004 赵六 14:00-21:00 1100 4 1005 周七 9:00-14:00 600 ''' # 查看第 1 3 4 行的数据 dataframe.iloc[[0,2,3],:] ''' 工号 姓名 时段 交易额 0 1001 张三 9:00-14:00 2000 2 1003 王五 9:00-14:00 800 3 1004 赵六 14:00-21:00 1100 ''' # 查看第 1 3 4 行的第 1 2 列 dataframe.iloc[[0,2,3],[0,1]] ''' 工号 姓名 0 1001 张三 2 1003 王五 3 1004 赵六 ''' # 查看前五行指定,姓名、时段和交易额的数据 dataframe[['姓名','时段','交易额']][:5] ''' 姓名 时段 交易额 0 张三 9:00-14:00 2000 1 李四 14:00-21:00 1800 2 王五 9:00-14:00 800 3 赵六 14:00-21:00 1100 4 周七 9:00-14:00 600 ''' dataframe[:5][['姓名','时段','交易额']] ''' 姓名 时段 交易额 0 张三 9:00-14:00 2000 1 李四 14:00-21:00 1800 2 王五 9:00-14:00 800 3 赵六 14:00-21:00 1100 4 周七 9:00-14:00 600 ''' # 查看第 2 4 5 行 姓名,交易额 数据 loc 函数 dataframe.loc[[1,3,4],['姓名','交易额']] ''' 姓名 交易额 1 李四 1800 3 赵六 1100 4 周七 600 ''' # 查看第四行的姓名数据 dataframe.at[3,'姓名'] # '赵六' # 查看交易额大于 1700 的数据 dataframe[dataframe['交易额'] > 1700] ''' 工号 姓名 时段 交易额 0 1001 张三 9:00-14:00 2000 1 1002 李四 14:00-21:00 1800 ''' # 查看交易额总和 dataframe.sum() ''' 工号 17055 姓名 张三李四王五赵六周七钱八钱八张三张三李四王五赵六周七钱八李四王五张三... 时段 9:00-14:0014:00-21:009:00-14:0014:00-21:009:00... 交易额 17410 dtype: object ''' # 某一时段的交易总和 dataframe[dataframe['时段'] == '14:00-21:00']['交易额'].sum() # 8300 # 查看张三在下午14:00之后的交易情况 dataframe[(dataframe.姓名 == '张三') & (dataframe.时段 == '14:00-21:00')][:10] ''' 工号 姓名 时段 交易额 7 1001 张三 14:00-21:00 600 ''' # 查看日用品的销售总额 # dataframe[dataframe['柜台'] == '日用品']['交易额'].sum() # 查看张三总共的交易额 dataframe[dataframe['姓名'].isin(['张三'])]['交易额'].sum() # 5200 # 查看交易额在 1500~3000 之间的记录 dataframe[dataframe['交易额'].between(1500,3000)] ''' 工号 姓名 时段 交易额 0 1001 张三 9:00-14:00 2000 1 1002 李四 14:00-21:00 1800 9 1002 李四 14:00-21:00 1500 '''
2025年05月29日
0 阅读
0 评论
0 点赞
2025-05-27
python零碎知识汇总
https://p1.ssl.qhimg.com/t010d1433ef39d6d0cf.jpg只获取当前目录下,剔除文件,只要文件夹名称import os dbtype_list = os.listdir(“sql_dir_war”) for dbtype in dbtype_list: if os.path.isfile(os.path.join(sql_dir_war,dbtype)): dbtype_list.remove(dbtype)sql_dir_war 是当前路径下文件夹的名字,如果直接是当前路径下可以输入dbtype_list = os.listdir()python实现在某本中某个关键词前插入一行def add_line_above(src_keyword,des_keyword,des_dir): logging.debug("\033[1;34m add_line_above \033[0m") for line in fileinput.input(des_dir,inplace=1): if src_keyword in line: print(des_keyword) print(line,end="")python实现在某本中某个关键词后插一行def add_line_below(src_keyword,des_keyword,des_dir): logging.debug("\033[1;34m add_line_below \033[0m") for line in fileinput.input(des_dir,inplace=1): print(line,end="") if src_keyword in line: print(des_keyword) python实现在某本中删除某两个个关键词之间的内容def delete_segment_exclude(src_keyword_begin,src_keyword_end,src_dir): line_begin = 0 line_end = 0 for line in fileinput.input(src_dir,inplace=0): if src_keyword_begin in line: line_begin = fileinput.filelineno() if src_keyword_end in line: line_end = fileinput.filelineno() temp_file=open(src_dir+"_temp",'w+') for line in fileinput.input(src_dir,inplace=0): cur_line = fileinput.filelineno() if(cur_line>line_begin)&(cur_line<line_end): continue else: temp_file.write(line) temp_file.close() shutil.move(src_dir+"_temp",src_dir)
2025年05月27日
0 阅读
0 评论
0 点赞
2025-05-20
PyQt5应用实例]获取城市天气预报
目录一、获取天气数据二、获取不同城市的天气预报API三、界面实现四、将界面文件转换为.py文件五、调用主窗口类六、使用PyInstaller打包项目生成EXE文件一、获取天气数据使用Python获取天气数据有两种方法:1、通过爬虫的方式,获取天气预报网站的HTML页面,然后使用XPath或BeautifulSoup解析HTML页面的内容;2、通过天气预报网站提供的API,直接获取结构化数据,省去了解析HTML页面这一步。本例使用中国天气网站提供的API,中国天气官网地址:http://www.weather.com.cn。获取天气数据使用的是Requests库,它是使用Python语言基于urllib编写的HTTP库,需要使用pip命令进行安装。pip install requestsRequests库包含一个名为json的方法,当请求的地址返回的是JSON格式的数据时,直接使用该方法访问即可,而不需要再使用Python标准库中的json库。二、获取不同城市的天气预报API请求地址是:http://www.weather.com.cn/data/sk/城市代码.html,部分城市代码:北京 101010100,上海 101020100,完整的城市代码可在网上搜索到(全国各个城市代码)。返回参数如下表所示。名称 描述weatherinfo weatherInfo消息根节点city 城市中文名cityid 城市IDtemp 温度WD 风向WS 风力SD 湿度WSE 风力time 发布时间rain 是否下雨,1:有雨,0:无雨isRadar 是否有雷达图,1:有雷达图,0:没有雷达图Radar 雷达图编号,雷达图地址:http://www.weather.com.cn/html/radar/雷达图编号.shtml测试代码:import requests if __name__ == "__main__": rep = requests.get("http://www.weather.com.cn/data/sk/101020100.html") rep.encoding = "utf-8" print("Result: %s" % rep.json()) print("City: %s" % rep.json()["weatherinfo"]["city"]) print("Wind Direction: %s" % rep.json()["weatherinfo"]["WD"]) print("Temperature: %s" % rep.json()["weatherinfo"]["temp"] + " °C") print("Wind Strength: %s" % rep.json()["weatherinfo"]["WS"]) print("Humidity: %s" % rep.json()["weatherinfo"]["SD"])输出结果:Result: {'weatherinfo': {'city': '上海', 'cityid': '101020100', 'temp': '23.5', 'WD': '东北风', 'WS': '小于3级', 'SD': '80%', 'AP': '1006.4hPa', 'njd': '2903', 'WSE': '<3', 'time': '17:00', 'sm': '1.1', 'isRadar': '1', 'Radar': 'JC_RADAR_AZ9210_JB'}}City: 上海Wind Direction: 东北风Temperature: 23.5 °CWind Strength: 小于3级Humidity: 80%查询天气的业务逻辑代码调试成功。三、界面实现使用Qt Designer来设计天气预报窗口,如下图所示:WeatherWin.ui代码:<?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>Form</class> <widget class="QWidget" name="Form"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>450</width> <height>347</height> </rect> </property> <property name="windowTitle"> <string>Form</string> </property> <widget class="QGroupBox" name="groupBox"> <property name="geometry"> <rect> <x>10</x> <y>10</y> <width>431</width> <height>251</height> </rect> </property> <property name="title"> <string>查询城市天气</string> </property> <widget class="QComboBox" name="weatherComboBox"> <property name="geometry"> <rect> <x>80</x> <y>30</y> <width>221</width> <height>21</height> </rect> </property> <item> <property name="text"> <string>北京</string> </property> </item> <item> <property name="text"> <string>天津</string> </property> </item> <item> <property name="text"> <string>上海</string> </property> </item> </widget> <widget class="QTextEdit" name="resultText"> <property name="geometry"> <rect> <x>10</x> <y>60</y> <width>411</width> <height>181</height> </rect> </property> </widget> <widget class="QLabel" name="label"> <property name="geometry"> <rect> <x>20</x> <y>30</y> <width>72</width> <height>21</height> </rect> </property> <property name="text"> <string>城市</string> </property> </widget> </widget> <widget class="QPushButton" name="queryBtn"> <property name="geometry"> <rect> <x>90</x> <y>300</y> <width>93</width> <height>28</height> </rect> </property> <property name="text"> <string>查询</string> </property> </widget> <widget class="QPushButton" name="clearBtn"> <property name="geometry"> <rect> <x>230</x> <y>300</y> <width>93</width> <height>28</height> </rect> </property> <property name="text"> <string>清空</string> </property> </widget> </widget> <resources/> <connections> <connection> <sender>clearBtn</sender> <signal>clicked()</signal> <receiver>Form</receiver> <slot>clearResult()</slot> <hints> <hint type="sourcelabel"> <x>270</x> <y>314</y> </hint> <hint type="destinationlabel"> <x>363</x> <y>288</y> </hint> </hints> </connection> <connection> <sender>queryBtn</sender> <signal>clicked()</signal> <receiver>Form</receiver> <slot>queryWeather()</slot> <hints> <hint type="sourcelabel"> <x>161</x> <y>313</y> </hint> <hint type="destinationlabel"> <x>64</x> <y>286</y> </hint> </hints> </connection> </connections> <slots> <slot>clearResult()</slot> <slot>queryWeather()</slot> </slots> </ui>控件说明如下表所示:四、将界面文件转换为.py文件使用pyuic5命令将界面文件转换成.py文件,转换后的Python文件名是WeatherWin.py。pyuic5 -o WeatherWin.py WeatherWin.ui转换后的WeatherWin.py完整代码如下:# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'weather.ui' # # Created by: PyQt5 UI code generator 5.15.4 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(450, 347) self.groupBox = QtWidgets.QGroupBox(Form) self.groupBox.setGeometry(QtCore.QRect(10, 10, 431, 251)) self.groupBox.setObjectName("groupBox") self.weatherComboBox = QtWidgets.QComboBox(self.groupBox) self.weatherComboBox.setGeometry(QtCore.QRect(80, 30, 221, 21)) self.weatherComboBox.setObjectName("weatherComboBox") self.weatherComboBox.addItem("") self.weatherComboBox.addItem("") self.weatherComboBox.addItem("") self.resultText = QtWidgets.QTextEdit(self.groupBox) self.resultText.setGeometry(QtCore.QRect(10, 60, 411, 181)) self.resultText.setObjectName("resultText") self.label = QtWidgets.QLabel(self.groupBox) self.label.setGeometry(QtCore.QRect(20, 30, 72, 21)) self.label.setObjectName("label") self.queryBtn = QtWidgets.QPushButton(Form) self.queryBtn.setGeometry(QtCore.QRect(90, 300, 93, 28)) self.queryBtn.setObjectName("queryBtn") self.clearBtn = QtWidgets.QPushButton(Form) self.clearBtn.setGeometry(QtCore.QRect(230, 300, 93, 28)) self.clearBtn.setObjectName("clearBtn") self.retranslateUi(Form) self.clearBtn.clicked.connect(Form.clearResult) self.queryBtn.clicked.connect(Form.queryWeather) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): _translate = QtCore.QCoreApplication.translate Form.setWindowTitle(_translate("Form", "Form")) self.groupBox.setTitle(_translate("Form", "查询城市天气")) self.weatherComboBox.setItemText(0, _translate("Form", "北京")) self.weatherComboBox.setItemText(1, _translate("Form", "天津")) self.weatherComboBox.setItemText(2, _translate("Form", "上海")) self.label.setText(_translate("Form", "城市")) self.queryBtn.setText(_translate("Form", "查询")) self.clearBtn.setText(_translate("Form", "清空")).五、调用主窗口类在主窗口类MainWindow中调用界面类Ui_Form,然后在主窗口类中添加查询天气的业务逻辑代码,这样就做到了界面显示和业务逻辑的分离。CallWeatherWin.py代码如下:# -*- coding: utf-8 -*- import sys from PyQt5.QtWidgets import QApplication , QMainWindow from WeatherWin import Ui_Form import requests class MainWindow(QMainWindow ): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.ui = Ui_Form() self.ui.setupUi(self) def queryWeather(self): print('* queryWeather ') cityName = self.ui.weatherComboBox.currentText() cityCode = self.transCityName(cityName) rep = requests.get('http://www.weather.com.cn/data/sk/' + cityCode + '.html') rep.encoding = 'utf-8' print( rep.json() ) msg1 = '城市: %s' % rep.json()['weatherinfo']['city'] + '\n' msg2 = '风向: %s' % rep.json()['weatherinfo']['WD'] + '\n' msg3 = '温度: %s' % rep.json()['weatherinfo']['temp'] + ' 度' + '\n' msg4 = '风力: %s' % rep.json()['weatherinfo']['WS'] + '\n' msg5 = '湿度: %s' % rep.json()['weatherinfo']['SD'] + '\n' result = msg1 + msg2 + msg3 + msg4 + msg5 self.ui.resultText.setText(result) def transCityName(self ,cityName): cityCode = '' if cityName == '北京' : cityCode = '101010100' elif cityName == '天津' : cityCode = '101030100' elif cityName == '上海' : cityCode = '101020100' return cityCode def clearResult(self): print('* clearResult ') self.ui.resultText.clear() if __name__=="__main__": app = QApplication(sys.argv) win = MainWindow() win.show() sys.exit(app.exec_()) 运行脚本,显示效果如下图所示。六、使用PyInstaller打包项目生成EXE文件我们使用PyQt5开发的程序并不一定是给自己使用的,也可能是给用户或者朋友用,使用者可能并不知道如何运行.py文件,这时候就有了把.py文件编译成.exe文件的需求。PyInstaller是一个很好用而且免费的打包工具,使用pip命令安装PyInstaller模块:pip install PyInstaller在命令行窗口中进入需要打包的代码所在的目录下,运行下面的命令:pyinstaller [opts] yourprogram.py可选的参数有:-F, -onefile, 打包成一个EXE文件-D, -onedir, 创建一个目录,包含EXE文件,但会依赖很多文件(默认选项)-c, -console, -nowindowed, 使用控制台,无窗口(默认)-w, -windowed, -noconsole,使用窗口,无控制台对于本例,进入CallWeatherWin.py文件所在的目录下,运行:pyinstaller -F -w CallWeatherWin.pyPyInstaller自动执行一系列的项目打包过程,最后生成EXE文件,在同目录下的dist子文件夹中生成了CallWeatherWin.exe文件。双击CallWeatherWin.exe文件,其运行效果与前面直接使用Python解释器运行CallWeatherWin.py的效果一样。———————————————— 版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。 原文链接:https://blog.csdn.net/sinat_16020825/article/details/120724216
2025年05月20日
0 阅读
0 评论
0 点赞
1
2
3