-1

嗨,到目前为止,我正在尝试使用 wasd 移动对象,直到让 wasd 启动一个函数,但我不知道如何实际移动对象。谢谢

希望有人能告诉我如何做到这一点

我还试图让较小的椭圆向右飞过屏幕

`
#new_game.py
from tkinter import *
import random
r = random
class window_one:
    def __init__ (self):

        Button(main_window,text="Start",command=self.start).grid()
        Button(main_window,text="Quit",command=self.quit).grid()
        Button(main_window,text="ball",command=self.dodge).grid()

    def quit(self):
        main_window.destroy()

    def start(self):
        x_val1 = 30
        x_val2 = x_val1 - 20
        y_val1 = 175
        y_val2 = y_val1 + 20
        self.dave = canvas.create_rectangle(30,175,10,195,fill="green")

        self.dodge
        canvas.update()

    def dodge(self):
        colorl = ["red","blue","green","yellow","purple"]
        y_val = r.randint(1,390)
        color = r.choice(colorl)
        canvas.create_oval(590,y_val,600,y_val+10,fill = color)

    def up(self):
        Canvas.move(start.dave,30,50)

    def down(self):
         print()

    def left(self):
        print()

    def right(self):
        print()

main_window = Tk()
canvas = Canvas(main_window,width=600,height=390,bg = "#ffffff")
canvas.grid()
window_one()

main_window.bind("<KeyPress-Left>",window_one.left) 
main_window.bind("<KeyPress-Right>",window_one.right) 
main_window.bind("<KeyPress-Up>",window_one.up) 
main_window.bind("<KeyPress-Down>",window_one.down)`
4

1 回答 1

0

要对键盘事件采取行动,您需要监听它们。请参考下面的简单示例(取自:https ://subscription.packtpub.com/book/web_development/9781788622301/1/ch01lvl1sec20/handling-mouse-and-keyboard-events )

import tkinter as tk 

class App(tk.Tk): 
    def __init__(self): 
        super().__init__() 
        entry = tk.Entry(self) 
        entry.bind("<FocusIn>", self.print_type)  
        entry.bind("<Key>", self.print_key) 
        entry.pack(padx=20, pady=20) 

    def print_type(self, event): 
        print(event.type) 

    def print_key(self, event): 
        args = event.keysym, event.keycode, event.char 
        #THIS WILL PRINT THE KEY ASSOCIATED WITH THE LAST CAPTURED EVENT
        print("Symbol: {}, Code: {}, Char: {}".format(*args)) 

if __name__ == "__main__": 
    app = App() 
    app.mainloop() 
于 2020-03-01T23:47:37.233 回答