简体   繁体   English

为什么Tkinter无法将函数正确绑定到事件?

[英]Why Tkinter doesn't bind a function to an event correctly?

I'm making a simple program in Python 3 by using Tkinter. 我正在使用Tkinter在Python 3中编写一个简单的程序。 We start with a black canvas in a full-screen tkinter window and I want to show a blue circle in the middle of the canvas when I press the space bar on my keyboard. 我们从全屏tkinter窗口中的黑色画布开始,当我按下键盘上的空格键时,我想在画布中间显示一个蓝色圆圈。

I tried this code: 我尝试了这段代码:

from tkinter import *

class TheBlueCircle:
    def __init__(self, master):
        self.master = master
        self.ws = master.winfo_screenwidth()
        self.hs = master.winfo_screenheight()
        self.master.geometry(str(self.ws)+'x'+str(self.ws)+'+0+0')
        self.canvas = Canvas(master, bg = 'black')
        self.canvas.pack(fill = BOTH, expand = True)
        self.canvas.bind('<KeyPress-space>', self.drawCircle)

    def drawCircle(self):
        r = min(self.ws, self.hs)/3
        coord = (self.ws/2-r, self.hs/2-r, self.ws/2+r, self.hs/2+r)
        self.canvas.create_oval(coord, fill = 'blue')

root = Tk()
TheBlueCircle(root)
root.mainloop()

But it doesn't work. 但这是行不通的。 No matter how many times I press the space bar. 无论我按多少次空格键。 It doesn't get to apply the drawCircle function. 不必应用drawCircle函数。

What is wrong? 怎么了?

There are some changes needed in your code. 您的代码中需要进行一些更改。 First you need to take an event as arg for your drawCircle method. 首先,您需要为drawCircle方法将一个event作为arg接收。 Secondly, the current focus is not set to the canvas object. 其次,当前焦点未设置到canvas对象。

To have your method correctly executed upon tabbing space , either first press tab when you launch your GUI, or force a focus change in your code: 要在制表tab space正确执行方法,请在启动GUI时先按Tab键,或在代码中强制更改焦点:

class TheBlueCircle:
    def __init__(self, master):
        ...
        self.canvas.bind('<space>', self.drawCircle)
        self.canvas.focus_set()

    def drawCircle(self,event=None):
        ...

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

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