如何将图像随机放置在tkinter画布网格中

时间:2016-11-20 17:16:15

标签: python canvas random tkinter tkinter-canvas

我试图创建一个游戏,其中图像放置在网格的随机单元格中。 我曾设法创建一个网格,我试图使用它来随机放置图像,但它似乎没有像我希望的那样工作。

try:
    import tkinter as tk
    from tkinter import ttk 
    from tkinter.ttk import *
except ImportError:
    import Tkinter as tk
    from Tkinter import ttk 
    from Tkinter.ttk import *
import random
from random import randint

window = tk.Tk() 
style = ttk.Style(window) 
style.configure("BW.TLabel")
game_frame = tk.Frame(window)
game_grid = tk.Canvas(game_frame, width=450, height=450, borderwidth=0,
                      highlightthickness=0)

def grid_create():
    global row, col, cell_width, cell_height, rect, rows , columns
    rows = 8 
    columns = 8 
    cell_width = 50 
    cell_height = 50 
    rect = {}
    for i in (game_grid, game_frame):
        i.pack()
    for column in range(8):
        for row in range(8):
            x1 = column*cell_width 
            y1 = row * cell_height 
            x2 = x1 + cell_width 
            y2 = y1 + cell_height 
            rect[row,column] = game_grid.create_rectangle(x1,y1,x2,y2,
                                                       fill="green",
                                                          tags="rect")
    grid_draw()
def grid_draw():
    global row, col
    game_grid.itemconfig("rect", fill="green")
    for i in range(8): 
        row = random.randint(0,8)
        col = random.randint(0,8)
    create_objects()
def create_objects():
    rows = 8 
    columns = 8 
    cell_width = 50 
    cell_height = 50 
    bandits = 5
    bandit_list = {}
    bandit_img = tk.PhotoImage(file="Bandit.png")

    for column in range(randint(0,8)):
        for row in range(randint(0,8)):
            x1 = column*cell_width + 22
            y1 = row * cell_height - 22
            x2 = x1 + cell_width 
            y2 = y1 + cell_height 
            bandit_list[row, column] = game_grid.create_image(x1, y2,
                                                              image=bandit_img)
    for i in range(randint(0,5)):
        row = random.randint(0,8)
        col = random.randint(0,8)
grid_create()
window.mainloop() 

我只想要五个强盗'在随机单元格中显示 - 因此bandits = 5 - 但我似乎无法弄清楚如何做到这一点。我也不想要任何强盗#39;重叠。任何帮助表示赞赏。

图片: Link to image as I do not have the required reputation to embed it here.

1 个答案:

答案 0 :(得分:1)

PhotoImage"Garbage Collector"存在问题,它会从功能中删除(从内存中)分配给局部变量的图像。

您必须将其分配给全局变量,即。

# create global variable
bandit_img = None

def create_objects():
    # inform function to use global varia
    global bandit_img

    bandit_img = tk.PhotoImage(file="Bandit.png")

或小部件实例:请参阅第http://effbot.org/tkinterbook/photoimage.htm页上的“注释”

要获得5个强盗,你必须得到随机值(row,col)并检查它是否在强盗列表中不存在。如果列表中存在(row,col),则会再次获取随机值并再次检查。当您找到唯一的while True

时,您可以使用break循环和(row,col)离开循环
try:
    import tkinter as tk
    import tkinter.ttk as ttk
except ImportError:
    import Tkinter as tk
    import ttk 

import random

# --- constants --- (UPPER_CASE names)

ROWS = 8 
COLUMNS = 8 
CELL_WIDTH = 50 
CELL_HEIGHT = 50
BANDITS_NUMBER = 5

# --- functions ---

def create_grid():

    data = {}

    for col in range(COLUMNS):
        for row in range(ROWS):
            x1 = col * CELL_WIDTH 
            y1 = row * CELL_HEIGHT
            x2 = x1 + CELL_WIDTH 
            y2 = y1 + CELL_HEIGHT
            data[row, col] = game_grid.create_rectangle(x1, y1, x2, y2,
                                                       fill="green", tags="rect")

    return data   

def create_bandits(image):

    data = {}

    for i in range(BANDITS_NUMBER):

        while True:
            row = random.randint(0, ROWS-1)
            col = random.randint(0, COLUMNS-1)
            if (row,col) not in data:
                break

        x1 = col * CELL_WIDTH + 22
        y1 = row * CELL_HEIGHT - 22
        x2 = x1 + CELL_WIDTH
        y2 = y1 + CELL_HEIGHT

        data[row, col] = game_grid.create_image(x1, y2, image=image)

    return data

# --- main ---

# - init -

window = tk.Tk() 

game_frame = tk.Frame(window)
game_frame.pack()

game_grid = tk.Canvas(game_frame, width=450, height=450, borderwidth=0,
                      highlightthickness=0)
game_grid.pack()
game_grid.itemconfig("rect", fill="green")

# - data -

rects = create_grid()

# create global variable
bandit_image = tk.PhotoImage(file="Bandit.png")

# send image to function - so you don't need word "global"
bandits = create_bandits(bandit_image)

# - start -

window.mainloop()
相关问题