帆布类Tkinter支持的功能是在任何画布或tkinter顶层将对象从一个位置移动到另一位置。
语法:Canvas.move(canvas_object, x, y)
参数:canvas_object是在Canvas类的帮助下创建的任何有效图像或图形。要知道如何使用Canvas类创建对象, 请参考此内容。
x是到左上角的水平距离。
y是距左上角的垂直距离。
我们将使用类来查看移动()方法。
类参数
使用的数据成员:主xy canvas矩形使用的成员函数:
Movement()left()right()up()down()使用的小部件:Canvas
Tkinter使用的方法:Canvas.create_rectangle()pack()Canvas.move()after( )bind()
以下是Python实现:
# imports every file form tkinter and tkinter.ttk
from tkinter import *
from tkinter.ttk import *
class GFG:
def __init__( self , master = None ):
self .master = master
# to take care movement in x direction
self .x = 1
# to take care movement in y direction
self .y = 0
# canvas object to create shape
self .canvas = Canvas(master)
# creating rectangle
self .rectangle = self .canvas.create_rectangle(
5 , 5 , 25 , 25 , fill = "black" )
self .canvas.pack()
# calling class's movement method to
# move the rectangle
self .movement()
def movement( self ):
# This is where the move() method is called
# This moves the rectangle to x, y coordinates
self .canvas.move( self .rectangle, self .x, self .y)
self .canvas.after( 100 , self .movement)
# for motion in negative x direction
def left( self , event):
print (event.keysym)
self .x = - 5
self .y = 0
# for motion in positive x direction
def right( self , event):
print (event.keysym)
self .x = 5
self .y = 0
# for motion in positive y direction
def up( self , event):
print (event.keysym)
self .x = 0
self .y = - 5
# for motion in negative y direction
def down( self , event):
print (event.keysym)
self .x = 0
self .y = 5
if __name__ = = "__main__" :
# object of class Tk, resposible for creating
# a tkinter toplevel window
master = Tk()
gfg = GFG(master)
# This will bind arrow keys to the tkinter
# toplevel which will navigate the image or drawing
master.bind( "<KeyPress-Left>" , lambda e: gfg.left(e))
master.bind( "<KeyPress-Right>" , lambda e: gfg.right(e))
master.bind( "<KeyPress-Up>" , lambda e: gfg.up(e))
master.bind( "<KeyPress-Down>" , lambda e: gfg.down(e))
# Infnite loop breaks only by interrupt
mainloop()
输出如下:
上面的代码中使用了额外的打印语句, 以显示移动()方法。键盘关键字(保留Tkinter)用于打印按下了哪个键盘键。
首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。
评论前必须登录!
注册