繁体   English   中英

如何为 python 中的 class 对象定义绑定?

[英]How to define binds for class objects in python?

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

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()

首先执行root.bind("<Button-3>",A.settings_menu)时, A还没有创建。 其次, Acreate_line()内部的局部变量,因此不能在 function 之外访问。

我建议在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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM