【问题标题】:Move object in python tkinter canvas在 python tkinter 画布中移动对象
【发布时间】:2017-08-24 23:20:59
【问题描述】:

所以我有一艘潜艇:

from tkinter import *
HEIGHT = 500
WIDTH = 800
window = Tk()
window.title("Bubble Blaster")
c = Canvas(window, width=WIDTH, height=HEIGHT, bg="darkblue")
c.pack()
ship_id = c.create_polygon(5, 5, 5, 25, 30, 15, fill="red")
ship_id2 = c.create_oval(0, 0, 30, 30, outline="red")  

我正在读一本关于如何使潜艇移动的书,这就是它所说的:

def move_ship(event):
    if event.keysym == "up":
        c.move(ship_id, 0, -ship_spd)
        c.move(ship_id2, 0, -ship_spd)
    elif event.keysym == "Down":
        c.move(ship_id, 0, ship_spd)
        c.move(ship_id2, 0, ship_spd)
    elif event.keysym == "Left":
        c.move(ship_id, -ship_spd, 0)
        c.move(ship_id2,  -ship_spd, 0)
    elif event.keysym == "Right":
        c.move(ship_id, ship_spd, 0)
        c.move(ship_id2,  ship_spd, 0)
    c.bind_all('<key', move_ship)

当我运行它时,它给了我一个错误:
PS.我在 sn-p 中这样做是因为 Ctrl+v 不会完成所有消息

<h4 style="color: red">Traceback (most recent call last):
  File "C:\Users\Bloxy Craft\Desktop\Bubble Blaster.py", line 28, in &lt;module&gt;
    c.bind_all('&lt;key&gt;', move_ship)
  File "C:\Users\Bloxy Craft\AppData\Local\Programs\Python\Python36\lib\tkinter\__init__.py", line 1257, in bind_all
    return self._bind(('bind', 'all'), sequence, func, add, 0)
  File "C:\Users\Bloxy Craft\AppData\Local\Programs\Python\Python36\lib\tkinter\__init__.py", line 1200, in _bind
    self.tk.call(what + (sequence, cmd))
_tkinter.TclError: bad event type or keysym "key"</h4>
有人可以帮我吗?
谢谢!
- Bloxy工艺

【问题讨论】:

  • 顺便说一下这本书的名字,帮助您的孩子进行计算机编码
  • &lt;key&gt;&lt;Key&gt; 不同。您需要使用&lt;Key&gt;

标签: python user-interface tkinter tkinter-canvas


【解决方案1】:

就像Bryan Oakley 说你需要用'&lt;Key&gt;' 替换'&lt;key'。此外,您还需要在代码中将 if event.keysym == "up": 替换为 if event.keysym == "Up":(“Up”中的 U 必须为大写字母)。孔代号为:

from tkinter import *
HEIGHT = 500
WIDTH = 800
window = Tk()
window.title("Bubble Blaster")
c = Canvas(window, width=WIDTH, height=HEIGHT, bg="darkblue")
c.pack()
ship_id = c.create_polygon(5, 5, 5, 25, 30, 15, fill="red")
ship_id2 = c.create_oval(0, 0, 30, 30, outline="red")

def move_ship(event):
    if event.keysym == "Up":
        c.move(ship_id, 0, -ship_spd)
        c.move(ship_id2, 0, -ship_spd)
    elif event.keysym == "Down":
        c.move(ship_id, 0, ship_spd)
        c.move(ship_id2, 0, ship_spd)
    elif event.keysym == "Left":
        c.move(ship_id, -ship_spd, 0)
        c.move(ship_id2,  -ship_spd, 0)
    elif event.keysym == "Right":
        c.move(ship_id, ship_spd, 0)
        c.move(ship_id2,  ship_spd, 0)

c.bind_all('<Key>', move_ship)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-28
    • 1970-01-01
    • 2013-04-19
    • 2023-03-12
    • 2022-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多