【发布时间】:2014-08-19 06:43:01
【问题描述】:
我正在玩一个小“游戏”,正在学习如何使用.bind(...),我遇到了一个我不明白的奇怪问题;似乎我的一些值在每次函数重复时增加量(每次 1 秒后)。我想这个游戏就像“猫捉老鼠”;你必须逃离追逐的对象。我已经为“猫”和“鼠标”使用了标签,你根据箭头键移动,另一个标签追你,但不是每次都追你相同的量(如预期的那样),它增加了第一个时间它移动一点,然后更多,更多......(几乎像指数一样),直到它移动了屏幕的一半,我不知道为什么要改变追逐者的x和y坐标每次加 1。
我也在使用全局变量(对于全局变量和糟糕/懒惰的编写代码,我很抱歉,我试图让它尽可能易于阅读,但它仍然不是很漂亮),使用全局变量可能是导致我的问题?
下面的链接是一个变量增加超过想要的增量,这是因为他们“模型中有两个代理”,一个调用另一个以错误的数量增加值...... 我在做这样的事情吗? Increment value increasing exponentially
这是我的代码:
import tkinter as tk
root = tk.Tk()
runner = tk.Label(text = 'RUN RUN RUN', bg = 'green')
global no1
global no2
no1 = 100
no2 = 100
runner.place(x = no1, y = no2)
def leftbutton(event):
global no1
no1 -= 5
runner.place(x = no1, y = no2)
def rightbutton(event):
global no1
no1 += 5
runner.place(x = no1, y = no2)
def upbutton(event):
global no2
no2 -= 5
runner.place(x = no1, y = no2)
def downbutton(event):
global no2
no2 += 5
runner.place(x = no1, y = no2)
global num1
global num2
num1 = 50
num2 = 50
chaser = tk.Label(bg = 'pink', text = 'Run or I will get you')
chaser.place(x = num1, y = num2)
global var
var = 2
def start():
global var
if var == 2:
begin.destroy()
var = 1
global num1
global num2
global no1
global no2
chaser.place(x = num1, y = num2)
if num1 > no1:
num1 -=1
root.after(1000, start)
if num1 < no1:
num1 += 1
root.after(1000, start)
if num2 > no2:
num2 -= 1
root.after(1000, start)
if num2 < no2:
num2 += 1
root.after(1000, start)
if num2 == no2 and num1 == no1:
root.destroy()
print('You Lose, GAME OVER')
begin = tk.Button(text = "BEGIN GAME", command = start)
begin.place(x = 1, y = 1)
root.bind("<Left>", leftbutton)
root.bind("<Right>", rightbutton)
root.bind("<Up>", upbutton)
root.bind("<Down>", downbutton)
root.mainloop()
【问题讨论】:
-
您调用
root.after(1000, start)两次:一次是在测试num1之后,一次是在测试num2之后。所以每次都会翻倍。 -
好的,大概就是这样,我只是检查一下,干杯
标签: python tkinter increment python-3.3