Python GUI编程入门(33)-PopupMenu和消息Dialog

mac2023-01-23  32

弹出菜单和消息对话框也是构成完成程序必不可少的部分,本文继续以FileBrowser为例进行说明。还是先看动作视频:

视频链接

首先获取选中文件信息的函数,它会在后续的处理中被调用。

 

 

def selected_files(): try: dir_node = tree_view.focus() if dir_node: path = node_path(dir_node) return path, map(lambda x:list_view.item(x, 'text'), list_view.selection()) except Exception as e: showerror('Error', str(e)) return None

处理主要分为两部分,一是通过tree_view的当前节点获取当前选中的目录路径,二是获取list_view中选中的文件名(可能是多个)。代码中使用迭代器的map方法将选中项目iid直接转换为文件名列表。

打开文件的处理很简单,只要依次打开选中的文件即可。startfile的功能就是使用操作系统默认应用打开文件。

 

 

def open_current(): path, selections = selected_files() if path: for fn in selections: os.startfile(os.path.join(path, fn))

删除选中文件的处理首先调用了一个askokcancel对话框确认用户的真实意图。用户确认之后再执行删除操作。异常处理是为了处理删除失败,例如视频中Word文件被打开的情况。当发生异常时,软件通过一个showerror对话框显示错误信息。

右键处理函数的内容如下:

 

 

def rbutton_down(event): iid = list_view.identify_row(event.y) if iid: if iid not in list_view.selection(): list_view.selection_set(iid) list_view.focus(iid) menu = Menu(list_view, tearoff=False) menu.add_command(label='Open', command=open_current) menu.add_command(label='Delete', command=delete_current) menu.post(event.x_root, event.y_root)  

鼠标右键处理函数唯一的一个参数负责传递鼠标消息,其中event.x和event.y是在对应逻辑窗口中的坐标,而evnet.x_root和event.y_root则是屏幕坐标。构建上下文菜单的过程和普通菜单相似,只是最后需要调用post方法启动菜单。这时传递给post方法的坐标需要使用屏幕坐标。

 

完整代码可以从以下地址下载:

https://github.com/xueweiguo/TkinterPrimer/blob/master/Sample/33%20PopupMenu.py

 

觉得本文有帮助?请分享给更多人。

阅读更多更新文章,请关注微信公众号【面向对象思考】

最新回复(0)