本文介绍了Tkinter/TTK - 防止字符串到 ButtonPress 转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个简单的脚本来创建一个 ttk Treeview(充当表格),当您双击它时,它会打开一个文件(路径保存在字典中)).但是,当您双击一行时,您会收到此错误:

I'm writing a simple script that creates a ttk Treeview (that acts as a table) and, when you double-click it, it opens a file (with the path saved in the dictionary). However, when you double-click a row you'll get this error:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\Maicol\AppData\Local\Programs\Python\Python36\lib\tkinter\__init__.py",
line 1699, in __call__
    return self.func(*args)
  File "C:\Users\Maicol\Documents\Projects\App_WINDOWS\School_Life_Diary\note.py",
line 195, in <lambda>
    lambda f=nt[x]["URIallegato"]: os.startfile(str(f)))
FileNotFoundError: [WinError 2] Can't find the specified file: '<ButtonPress event state=Mod1 num=1 x=677 y=37>'

问题是这段代码:

t.bind("<Double-1>", lambda f=nt[x]["URIallegato"]: os.startfile(str(f)))

允许双击和打开文件.

这是完整的Treeview代码:

t=Treeview(w)
t.pack(padx=10,pady=10)
for x in list(nt.keys()):
    t.insert("",x,text=nt[x]["allegati"])
    if nt[x]["allegati"]!="":
        t.bind("<Double-1>",
               lambda f=nt[x]["URIallegato"]: os.startfile(str(f)))

推荐答案

当事件触发时,tkinter 将传递一个事件对象.您正在尝试打开该事件对象,就好像它是一个文件一样.

When the event fires, tkinter will pass along an event object. You are trying to open that event object as if it were a file.

这是为什么?让我们首先将您的 lambda 重写为适当的函数.你的 lambda 相当于这个函数:

Why is that? Let's start by rewriting your lambda as a proper function. Your lambda is the equivalent of this function:

def handle_event(f=default_value):
    os.startfile(str(default_value))

当事件触发时,它的作用相当于:

When the event fires, it does the equivalent of this:

handle_event(event)

您的脚本有一个位置参数,event,它被分配给第一个关键字参数.因此 fevent 相同.

Your script is given a single positional argument, event, which is assigned to the first keyword argument. Thus f is the same as event.

解决方案是确保您的 lambda 接受事件,它可以简单地忽略:

The solution is to make sure your lambda accepts the event, which it can simply ignore:

lambda event, f=nt[x]["URIallegato"]: os.startfile(str(f)))

使用上述内容,event 对象将与 event 参数相关联,并且 f 的默认值将作为 f.

With the above, the event object will be associated with the event parameter, and your default value for f will be passed as f.

这篇关于Tkinter/TTK - 防止字符串到 ButtonPress 转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 14:51