自动移动形状?Python 3.5 Tkinter [英] Automatically Moving Shape? Python 3.5 Tkinter

查看:37
本文介绍了自动移动形状?Python 3.5 Tkinter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中,我目前正在使用tkinter进行游戏",但它决定不起作用.我想做的是用鼠标移动一个矩形,而另一个矩形则连续不断地上下移动,而玩家无需做任何事情.这是我的代码:

In python, I am currently making a 'game' using tkinter, but it has decided not to work. What I am trying to do is have one rectangle movable by the mouse, and the other rectangle that moves up and down continuously without the player doing anything. Here is my code:

from tkinter import *
import time
root = Tk()
root.title("Game")
root.geometry("800x800")

def motion():
    canvas.delete(ALL)
    a = canvas.create_rectangle(event.x-50, event.y-50, event.x+50, event.y+50, fill='red')

def motion2():
    b = canvas.create_rectangle(10, 100, 100, 10, fill='blue')
    y = -15
    x = 0
    time.sleep(0.025)
    canvas.move(b, x, -y)
    canvas.update()

canvas = Canvas(root, width=1000, height=5000, bg='white')
canvas.bind("<Motion>", motion)
canvas.pack(pady=0)

mainloop()

我希望这可以尽快解决.在过去的几天里,我一直在努力,仍然没有答案.谢谢您的时间:)-杰克

I hope this can be resolved soon. I've been working on this for the past few days, still no answer. Thanks for your time :) -Jake

推荐答案

您可以使用 root.after(毫秒,function_name)定期运行函数,也可以使用 canvas.move(object_id,offset_x,offset_y)以自动移动对象.

You can use root.after(milliseconds, function_name) to run function periodically and it can use canvas.move(object_id, offset_x, offset_y) to move object automatically.

然后您可以使用 canvas.coords(object_id,x1,y1,x2,y2)使用鼠标位置来设置新位置. bind 使用一个参数(对象 event )执行函数,因此函数必须接收该参数.

And you can use canvas.coords(object_id, x1, y1, x2, y2) to set new position using mouse position. bind exeecutes function with one argument (object event) so function has to receive this argument.

import tkinter as tk

# --- functions ---

def move_a(event):
    canvas.coords(a, event.x-50, event.y-50, event.x+50, event.y+50)

def move_b():
    canvas.move(b, 1, 0)
    # move again after 25ms (0.025s)
    root.after(25, move_b)

# --- main ---

# init
root = tk.Tk()

# create canvas
canvas = tk.Canvas(root)
canvas.pack()

# create objects
a = canvas.create_rectangle(0, 0, 100, 100, fill='red')
b = canvas.create_rectangle(0, 0, 100, 100, fill='blue')

# start moving `a` with mouse
canvas.bind("<Motion>", move_a)

# start moving `b` automatically
move_b()

# start program
root.mainloop()


要上下移动,您必须使用具有 speed 的变量,以便可以将其从 speed 更改为-速度,然后再次设置为速度.您还可以使用 move_down = True/False 检查当前方向(或者您可以使用 speed 检查方向,但是 b_move_down 更具可读性为人)


to move up and down you have to use variable with speed so you can change it from speed to -speed and againt to speed. And you can also use move_down = True/False to check current direction (or you can use speed to check direction but b_move_down can be more readable for people)

import tkinter as tk

# --- functions ---

def move_a(event):
    canvas.coords(a, event.x-50, event.y-50, event.x+50, event.y+50)

def move_b():
    # inform function to use external/global variable 
    # because we use `=` to change its value
    global b_speed
    global b_move_down

    canvas.move(b, 0, b_speed)

    # get current position        
    x1, y1, x2, y2 = canvas.coords(b)

    # check if you have to change direction
    #if b_speed > 0:
    if b_move_down:
        # if it reachs bottom
        if y2 > 300:
            # change direction
            #b_move_down = False
            b_move_down = not b_move_down
            b_speed = -b_speed
    else:
        # if it reachs top
        if y1 < 0:
            # change direction
            #b_move_down = True
            b_move_down = not b_move_down
            b_speed = -b_speed

    # move again after 25 ms (0.025s)
    root.after(25, move_b)

# --- main ---

# init
root = tk.Tk()

# create canvas
canvas = tk.Canvas(root, width=500, height=300)
canvas.pack()

# create objects
a = canvas.create_rectangle(0, 0, 100, 100, fill='red')
b = canvas.create_rectangle(0, 0, 100, 100, fill='blue')
# create global variables
b_move_down = True
b_speed = 5

# start moving `a` with mouse
canvas.bind("<Motion>", move_a)

# start moving `b` automatically
move_b()

# start program
root.mainloop()


编辑:在画布上移动

import tkinter as tk

# --- functions ---

def move_a(event):
    canvas.coords(a, event.x-50, event.y-50, event.x+50, event.y+50)

def move_b():
    # inform function to use external/global variable 
    # because we use `=` to change its value
    global b_speed_x
    global b_speed_y
    global b_direction

    canvas.move(b, b_speed_x, b_speed_y)

    # get current position        
    x1, y1, x2, y2 = canvas.coords(b)

    if b_direction == 'down':
        if y2 >= 300:
            b_direction = 'right'
            b_speed_x = 5
            b_speed_y = 0
    elif b_direction == 'up':
        if y1 <= 0:
            b_direction = 'left'
            b_speed_x = -5
            b_speed_y = 0
    elif b_direction == 'right':
        if x2 >= 500:
            b_direction = 'up'
            b_speed_x = 0
            b_speed_y = -5
    elif b_direction == 'left':
        if x1 <= 0:
            b_direction = 'down'
            b_speed_x = 0
            b_speed_y = 5

    # move again after 25 ms (0.025s)
    root.after(25, move_b)

# --- main ---

# init
root = tk.Tk()

# create canvas
canvas = tk.Canvas(root, width=500, height=300)
canvas.pack()

# create objects
a = canvas.create_rectangle(0, 0, 100, 100, fill='red')
b = canvas.create_rectangle(0, 0, 100, 100, fill='blue')
# create global variables
b_direction = 'down'
b_speed_x = 0
b_speed_y = 5

# start moving `a` with mouse
canvas.bind("<Motion>", move_a)

# start moving `b` automatically
move_b()

# start program
root.mainloop()


最后一个示例-键 p 暂停游戏


last example - key p pauses game

#!/usr/bin/env python3

import tkinter as tk

# --- constants --- (UPPER_CASE names)

DISPLAY_WIDHT = 800
DISPLAY_HEIGHT = 600

# --- classes --- (CamelCase names)

#class Player():
#    pass

#class BlueEnemy():
#    pass

# --- functions --- (lower_case names)

def move_a(event):
    # don't move if gama paused
    if not game_paused:
        canvas.coords(a, event.x-50, event.y-50, event.x+50, event.y+50)

def move_b():
    # inform function to use external/global variable
    # because we use `=` to change its value
    global b_speed_x
    global b_speed_y
    global b_direction

    # don't move if gama paused
    if not game_paused:
        canvas.move(b, b_speed_x, b_speed_y)

        # get current position
        x1, y1, x2, y2 = canvas.coords(b)

        if b_direction == 'down':
            if y2 >= DISPLAY_HEIGHT:
                b_direction = 'right'
                b_speed_x = 5
                b_speed_y = 0
        elif b_direction == 'up':
            if y1 <= 0:
                b_direction = 'left'
                b_speed_x = -5
                b_speed_y = 0
        elif b_direction == 'right':
            if x2 >= DISPLAY_WIDHT:
                b_direction = 'up'
                b_speed_x = 0
                b_speed_y = -5
        elif b_direction == 'left':
            if x1 <= 0:
                b_direction = 'down'
                b_speed_x = 0
                b_speed_y = 5

    # move again after 25 ms (0.025s)
    root.after(25, move_b)

def pause(event):
    global game_paused

    # change True/False
    game_paused = not game_paused

    if game_paused:
        # center text on canvas
        canvas.coords(text_pause, DISPLAY_WIDHT//2, DISPLAY_HEIGHT//2)
    else:
        # move text somewhere outside canvas
        canvas.coords(text_pause, -1000, -1000)

# --- main --- (lower_case names)

# init
root = tk.Tk()

# key `p` pause game
game_paused = False
root.bind('p', pause)

# create canvas
canvas = tk.Canvas(root, width=DISPLAY_WIDHT, height=DISPLAY_HEIGHT)
canvas.pack()

# create objects
a = canvas.create_rectangle(0, 0, 100, 100, fill='red')
b = canvas.create_rectangle(0, 0, 100, 100, fill='blue')
# create global variables
b_direction = 'down'
b_speed_x = 0
b_speed_y = 5

# start moving `a` with mouse
canvas.bind("<Motion>", move_a)

# start moving `b` automatically
move_b()

# create text somewhere outside canvas - so it will be "invisible"
text_pause = canvas.create_text(-1000, -1000, text="PAUSED", font=(50,))

# start program
root.mainloop()

这篇关于自动移动形状?Python 3.5 Tkinter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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