[英]Making a 5x5 Board using a grid in Tkinter
我使用 python、tkinter 和枕頭制作了我的第一個程序。
該程序應該隨機選擇四個平鋪圖像中的一個,創建一個圖像並重復 25 次使用網格制作 5x5 板將圖像定位在一個正方形中。
這不是我運行代碼時發生的情況
通常生成一兩列和 4 行,並不是每個坐標都用圖像填充。
出於某種原因,只有圖像的角落可見?
圖像中心似乎位於其網格的左上角。
輸出可能看起來像這樣
X = 用圖像填充的坐標
O = 用 bg 顏色填充的坐標
XX
牛
牛
當我希望它看起來像這樣
XXXXX
XXXXX
XXXXX
XXXXX
XXXXX
應該放置圖像的代碼如下所示
while n < 25:
n = n + 1
number = random.randint(1,4)
if number == 1:
TILE_FLOWER.grid(row = x, column = y)
TILE_FLOWER.create_image(16,16, image = TILE_FLOWER_IMG)
elif number == 2:
TILE_GRASS.grid(row = x, column = y)
TILE_GRASS.create_image(16,16, image = TILE_GRASS_IMG)
elif number == 3:
TILE_STONE.grid(row = x, column = y)
TILE_STONE.create_image(16,16, image = TILE_STONE_IMG)
elif number == 4:
TILE_WATER.grid(row = x, column = y,)
TILE_WATER.create_image(16,16, image = TILE_WATER_IMG)
if x == 5:
x = 0
y = y + 1
else:
x = x + 1
win.mainloop()
定義我的畫布的代碼如下所示
它們與我想在其上繪制的圖像大小相同。
TILE_FLOWER = Canvas(win, height = 80, width = 80)
TILE_GRASS = Canvas(win, height = 80, width = 80)
TILE_STONE = Canvas(win, height = 80, width = 80)
TILE_WATER = Canvas(win, height = 80, width = 80)
最后定義圖像的代碼如下所示
TILE_FLOWER_IMG = PhotoImage(file = 'Path1.png')
TILE_GRASS_IMG = PhotoImage(file = 'Path2.png')
TILE_STONE_IMG = PhotoImage(file = 'Path3.png')
TILE_WATER_IMG = PhotoImage(file = 'Path4.png')
希望我寫的有道理!
如果有人能幫我解決這個爛攤子,我將不勝感激:)
您需要在 5x5 網格的每個單元格中創建新的Label
或Canvas
:
import tkinter as tk
import random
root = tk.Tk()
imagelist = [
tk.PhotoImage(file='Path1.png'),
tk.PhotoImage(file='Path2.png'),
tk.PhotoImage(file='Path3.png'),
tk.PhotoImage(file='Path4.png'),
]
for i in range(25):
image = random.choice(imagelist)
tk.Label(root, image=image, width=80, height=80, bg='white').grid(row=i//5, column=i%5)
'''
# or using Canvas
canvas = tk.Canvas(root, width=80, height=80, bg='white')
canvas.create_image(40, 40, image=image)
canvas.grid(row=i//5, column=i%5)
'''
root.mainloop()
或者使用單個Canvas
:
canvas = tk.Canvas(root, width=400, height=400, bg='white')
canvas.pack()
for i in range(25):
image = random.choice(imagelist)
row = i // 5
col = i % 5
canvas.create_image(40+col*80, 40+row*80, image=image)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.