简体   繁体   中英

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

I'm making a simple program in Python 3 by using Tkinter. 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.

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.

What is wrong?

There are some changes needed in your code. First you need to take an event as arg for your drawCircle method. Secondly, the current focus is not set to the canvas object.

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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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