Python:当x和y的值发生变化时,如何获取多个(x,y)坐标?

时间:2014-07-01 11:48:25

标签: python-2.7 tkinter

在我制作的游戏中,我需要存储x和y坐标列表,但列表仅存储最后一次迭代。如何使其存储所有迭代?我使用的代码在这里:

from Tkinter import *
import Tkinter as tk
import random
screen = tk.Tk(className = "Battle Ship Game" )
screen.geometry("300x300")
screen["bg"] = "white"

line1= list()
choosing = 0

def choice(x,y) :
    global choises
    choises = {}
    global list2
    list2 = []
    list2.append((x,y))
    print list2
    return list2

def buildaboard1(screen) :
    x = 20
    for n in range(0,10) :
        y = 20
        for i in range(0,10) :
            line1.append(tk.Button(screen ))
            line1[-1].place( x = x , y = y+20 , height = 20 , width = 20 )
            a = x
            b = y
            line1[-1]["command"] = (lambda a = x , b = y :choice (a , b))

            y = y+20
        x = x +20
choosing = choosing +1

while (choosing < 5) :
    buildaboard1(screen)
    choosing  = choosing +1
computer_choises
screen.mainloop()

1 个答案:

答案 0 :(得分:1)

list2全球化。现在,您在添加新的list2

之前清除list2 = [](制作(x,y)

我的版本 - 我将名称list2更改为interactions

我做了其他修改。

from Tkinter import *
import Tkinter as tk
import random
screen = tk.Tk(className = "Battle Ship Game" )

screen.geometry("300x300")
screen["bg"] = "white"

board= []
choises = {}
interactions = []

def choice(x,y) :
    global interactions

    interactions.append((x,y))
    print interactions

    return interactions # you don't have to return global variable

def build_board(screen) :
    size = 20
    x = 20
    for __ in range(10):
        y = 20
        for __ in range(10):
            bt = tk.Button(screen, command=lambda a=x,b=y:choice(a, b))
            bt.place( x=x, y=y+size, height=size , width=size )
            board.append(bt)
            y += size
        x += size
    #print x, y

# I don't know why you create board many times - create once.
# Now you have buttons over buttons 
# because you don't remove old buttons before you create new board.
for choosing in range(1,5):
    build_board(screen)

#computer_choises

screen.mainloop()

编辑:在当前版本中,您不需要choice(),因为您可以使用

bt = tk.Button(screen, command=lambda a=x,b=y:interactions.append((a,b)))