如何在Tkinter(Python)中将空格键绑定到特定方法 [英] How to bind spacebar key to a certain method in tkinter (python)

查看:753
本文介绍了如何在Tkinter(Python)中将空格键绑定到特定方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用python开发一个项目,并且我开发了一种在tkinter中绘制特定内容的方法.我想要它,以便每当我按下空格键时,图像都会重绘自身(再次运行该方法,因为我对方法进行了编码,以便可以在其自身上方重绘).我如何将空格键绑定到方法上,以便在按下空格键时程序可以运行,绘制和重新绘制?

I am working on a project in python, and I made a method to draw a specific thing in tkinter. I want it so that whenever I press the spacebar, the image will redraw itself (run the method again because I coded the method so that it could redraw over itself). How exactly would I bind the spacebar to the method so that the program would run, draw, and re-draw if I pressed the spacebar?

例如,我想要它,以便每当我按下空格键时,程序便会在画布上的一个随机位置绘制

for example, i want it so that whenever I press space, the program draws in a random location on the canvas:

from Tkinter import *
from random import *

root=Tk()
canvas=Canvas(root,width=400,height=300,bg='white')
def draw():
    canvas.delete(ALL)# clear canvas first
    canvas.create_oval(randint(0,399),randint(0,299),15,15,fill='red')
draw()
canvas.pack()
root.mainloop()

我如何将空格键绑定到方法?

how would i bind the spacebar to the method?

推荐答案

from Tkinter import *
from random import *

root=Tk()
canvas=Canvas(root,width=400,height=300,bg='white')
def draw(event=None):
    canvas.delete(ALL)# clear canvas first
    canvas.create_oval(randint(0,399),randint(0,299),15,15,fill='red')
draw()
canvas.pack()

root.bind("<space>", draw)
root.mainloop()

这篇关于如何在Tkinter(Python)中将空格键绑定到特定方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆