【问题标题】:How to define binds for class objects in python?如何在python中为类对象定义绑定?
【发布时间】:2020-12-12 10:27:53
【问题描述】:

我正在尝试为在函数中创建的类对象定义绑定按钮。 因此,我在这里编写简单的代码。当我按下“线路按钮”时,它会在类方法中创建新实例。在“init 方法”中,我正在验证它。但是,当我按右键单击(按钮 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()

【问题讨论】:

    标签: python function class tkinter binding


    【解决方案1】:

    首先在执行root.bind("&lt;Button-3&gt;",A.settings_menu) 时,A 尚未创建。其次,Acreate_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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-05
      • 2011-04-05
      • 2015-10-08
      • 1970-01-01
      • 1970-01-01
      • 2013-02-20
      • 1970-01-01
      相关资源
      最近更新 更多