首页 > 解决方案 > 如何在python中为类对象定义绑定?

问题描述

我正在尝试为在函数中创建的类对象定义绑定按钮。因此,我在这里编写简单的代码。当我按下“线路按钮”时,它会在类方法中创建新实例。在“初始化方法”中,我正在验证它。但是,当我按右键单击(按钮 3)时,它会出错。它无法访问我在“create_line”函数中创建的类实例。我怎么解决这个问题?我也对其他想法持开放态度,比如在课堂上定义绑定函数?

from tkinter import *

class line_class():

    def __init__(self,line_no):
        self.line_number=line_no
        print(self.line_number)

    def settings_menu(self, event):   
        print(self.line_number, ": line entered")

def create_line():
    A=line_class(my_canvas.create_line(200, 200, 100, 100, fill='red', width=5, capstyle=ROUND, joinstyle=ROUND))
    
root = Tk()
root.title('Moving objects')
root.resizable(width=False, height=False)
root.geometry('1200x600+200+50')
root.configure(bg='light green')

my_canvas = Canvas(root, bg='white', height=500, width=700)
my_canvas.pack()

btn_line = Button(root, text='Line', width=30, command=lambda: create_line())
btn_line.place(relx=0,rely=0.1)

root.bind("<Button-3>",A.settings_menu)

root.mainloop()

标签: pythonfunctionclasstkinterbinding

解决方案


第一次root.bind("<Button-3>",A.settings_menu)执行时,A尚未创建。其次,A内部是局部变量,create_line()因此无法在函数外部访问。

我建议在里面定义绑定line_class,并使用my_canvas.tag_bind(...)而不是root.bind(...)

from tkinter import *

class line_class():
    def __init__(self,line_no):
        self.line_number=line_no
        print(self.line_number)
        
        my_canvas.tag_bind(line_no, "<Button-3>", self.settings_menu)

    def settings_menu(self, event):   
        print(self.line_number, ": line entered")

def create_line():
    line_class(my_canvas.create_line(200, 200, 100, 100, fill='red', width=5, capstyle=ROUND, joinstyle=ROUND))
    
root = Tk()
root.title('Moving objects')
root.resizable(width=False, height=False)
root.geometry('1200x600+200+50')
root.configure(bg='light green')

my_canvas = Canvas(root, bg='white', height=500, width=700)
my_canvas.pack()

btn_line = Button(root, text='Line', width=30, command=create_line)
btn_line.place(relx=0,rely=0.1)

root.mainloop()

推荐阅读