AttributeError:“Event”对象没有属性“Text1”

2024-09-30 08:28:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我的目的是通过TkinterText控件获得鼠标选中的文本。在

部分代码:

self.Text1 = Text(top)
self.Text1.place(relx=0.07, rely=0.09, relheight=0.04, relwidth=0.34)
self.Text1.configure(background="white")
self.Text1.configure(font="TkTextFont")
self.Text1.configure(foreground="black")
self.Text1.configure(highlightbackground="#d9d9d9")
self.Text1.configure(highlightcolor="black")
self.Text1.configure(insertbackground="black")
self.Text1.configure(selectbackground="#c4c4c4")
self.Text1.configure(selectforeground="black")
self.Text1.configure(width=294)
self.Text1.configure(wrap=WORD)

self.Scrolledtext1 = ScrolledText(top)
self.Scrolledtext1.place(relx=0.46, rely=0.19, relheight=0.62
        , relwidth=0.4)
self.Scrolledtext1.configure(background="white")
self.Scrolledtext1.configure(font="TkTextFont")
self.Scrolledtext1.configure(foreground="black")
self.Scrolledtext1.configure(highlightbackground="#d9d9d9")
self.Scrolledtext1.configure(highlightcolor="black")
self.Scrolledtext1.configure(insertbackground="black")

def button_down(self,):
    global s
    s = self.Text1.index('@%s,%s wordstart' % (event.x, event.y))

def button_up(self, ):
    global e
    e = self.Text1.index('@%s,%s wordend' % (event.x, event.y))


def test(self,):
    print(self.Scrolledtext1.get(s,e))

self.Scrolledtext1.bind("<Button-1>", button_down)
self.Scrolledtext1.bind("<ButtonRelease-1>", button_up)
self.Button2.configure(command=test(self,))

Tkinter回调中出现异常:

screenshot of traceback showing exception being generated

^{pr2}$

Tags: selfeventconfiguretopdefplacebuttonblack
1条回答
网友
1楼 · 发布于 2024-09-30 08:28:59

您的button_upbutton_downtest函数不是绑定方法。因此,它们没有得到self参数。作为self传递的值实际上是一个事件对象。由于您在函数中使用了self,我建议将它们更改为being-bound方法。我假设您发布的代码在__init__方法中。如果是,请将最后三行改为:

self.Scrolledtext1.bind("<Button-1>", self.button_down)
self.Scrolledtext1.bind("<ButtonRelease-1>", self.button_up)
self.Button2.configure(command=self.test)

并将这三个函数移为类的成员:

^{pr2}$

示例

这就是你的课之后应该看起来的样子。三个事件处理程序函数都在类中。在

class YourClassName:
    def __init__(self, *args, **kwargs):
        # initialization code
        # ...

        self.Scrolledtext1.bind("<Button-1>", self.button_down)
        self.Scrolledtext1.bind("<ButtonRelease-1>", self.button_up)
        self.Button2.configure(command=self.test)

    def button_down(self, event):
        global s
        s = self.Text1.index('@%s,%s wordstart' % (event.x, event.y))

    def button_up(self, event):
        global e
        e = self.Text1.index('@%s,%s wordend' % (event.x, event.y))


    def test(self, event):
        print(self.Scrolledtext1.get(s,e))

相关问题 更多 >

    热门问题