回答編集履歴
1
補足を追加
answer
CHANGED
@@ -1,5 +1,3 @@
|
|
1
|
-
プログラムが「思っている通り」に動かないということですね。実は、プログラムは「書いたとおり」に動きます。
|
2
|
-
|
3
1
|
以下の2箇所を修正してください。
|
4
2
|
|
5
3
|
- ↓キー入力時の判定を行なう文字列に余分な空白が混入しており、判定に失敗する。
|
@@ -13,4 +11,51 @@
|
|
13
11
|
```Diff
|
14
12
|
-root.bind("KeyRelease>",key_up)
|
15
13
|
+root.bind("<KeyRelease>",key_up)
|
14
|
+
```
|
15
|
+
修正後のプログラムは以下の通りです。
|
16
|
+
|
17
|
+
```Python
|
18
|
+
import tkinter
|
19
|
+
|
20
|
+
key = ""
|
21
|
+
|
22
|
+
|
23
|
+
def key_down(e):
|
24
|
+
global key
|
25
|
+
key = e.keysym
|
26
|
+
|
27
|
+
|
28
|
+
def key_up(e):
|
29
|
+
global key
|
30
|
+
key = ""
|
31
|
+
|
32
|
+
|
33
|
+
cx = 400
|
34
|
+
cy = 300
|
35
|
+
|
36
|
+
|
37
|
+
def main_proc():
|
38
|
+
global cx, cy
|
39
|
+
if key == "Up":
|
40
|
+
cy = cy - 20
|
41
|
+
if key == "Down":
|
42
|
+
cy = cy + 20
|
43
|
+
if key == "Left":
|
44
|
+
cx = cx - 20
|
45
|
+
if key == "Right":
|
46
|
+
cx = cx + 20
|
47
|
+
canvas.coords("MYCHR", cx, cy)
|
48
|
+
root.after(100, main_proc)
|
49
|
+
|
50
|
+
|
51
|
+
root = tkinter.Tk()
|
52
|
+
root.title("移動するネコ")
|
53
|
+
root.bind("<KeyPress>", key_down)
|
54
|
+
root.bind("<KeyRelease>", key_up)
|
55
|
+
canvas = tkinter.Canvas(width=800, height=600, bg="lightgreen")
|
56
|
+
canvas.pack()
|
57
|
+
img = tkinter.PhotoImage(file="mimi.png")
|
58
|
+
canvas.create_image(cx, cy, image=img, tag="MYCHR")
|
59
|
+
main_proc()
|
60
|
+
root.mainloop()
|
16
61
|
```
|