Tkinter 绑定事件没有调用函数

时间:2021-03-19 15:52:10

标签: python-3.x tkinter

我有这个代码:

    from tkinter import *

class logic():
    def createComponent(self, event):
        print("{0},{1}".format(event.x,event.y))

class gui(logic):
    window = Tk()
    obj = logic()

    def initGui(self):
        gui.window.mainloop()

    def onClick(self):
        gui.window.bind("<Button-1>",gui.obj.createComponent)

obj2 = gui()
obj2.initGui()
while True:
    obj2.onClick()

理论上这段代码应该在 lmb 单击时打印鼠标坐标,但由于某种原因没有调用“createComponent”(也没有错误)。我做错了什么?

1 个答案:

答案 0 :(得分:1)

修复了代码:

  • window.mainloop() 已经是一个循环,把它放在 while True 中会破坏代码
  • 课程设置错误
from tkinter import *

window = Tk()

def createComponent(event):
    print("{0},{1}".format(event.x,event.y))

window.bind("<Button-1>", createComponent)

window.mainloop()

面向对象:

from tkinter import *


class windFuncs:
    def createComponent(event):
        print("{0},{1}".format(event.x,event.y))

class wind(Tk):
    pass
    

window = wind()

window.bind("<Button-1>", windFuncs.createComponent)

window.mainloop()

您可能希望将 createComponent 放入 class wind