python - 如何在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()
解决方案
第一次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()
推荐阅读
- scala - 在 Scala 中调用其他对象的主要方法
- dart - 无法修复:没有为“Firebase auth”类定义 signInWithGoogle
- node.js - 将标题元素添加到 paperjs SVG(使用 node.js)
- python - 从应用引擎访问谷歌云存储帐户对象
- ios - 应用程序通过 MDM 分发时的 Key Chain 数据丢失
- javascript - 如何将 angular2+ 应用程序作为简单的 JS 文件集成到现有的 HTML 站点中
- graph - 确定是否在正在运行的计划任务中的方法?
- python - 获取 AttributeError:“NoneType”对象没有属性“键盘”,
- d3.js - 如何获取 D3 Axis 的路径字符串
- java - Spring 数据 Neo4j + Kotlin 上的日期转换器