【发布时间】:2020-06-24 09:18:31
【问题描述】:
我正在开发一个跳棋游戏 GUI,但我似乎无法弄清楚为什么它总是打开两个窗口而不是我初始化的那个。 这是我的代码:https://pastebin.com/s7XWLdfY 这是截图:link
任何帮助将不胜感激,我对 tkinter 还很陌生。
def init():
global root
global extraref #creates a reference to the pieces images
#so they don't get garbage collected
extraref = np.array([tk.Label() for item in range(64)]).reshape(8, 8)
def switch(board, val):
switcher = {
Board.E: "imgs/E.gif",
Board.W: "imgs/W.gif",
Board.B: "imgs/B.gif",
Board.DW: "imgs/DW.gif",
Board.DB: "imgs/DB.gif",
}
return switcher.get(val)
def refresh(board): #refreshes the board after a turn
mat = board.getMat()
#print(mat)
for i in range(8):
for j in range(8):
path = switch(board, mat[i][j])
#path = "imgs/B.gif"
tmp_img = Image.open(path)
img = itk.PhotoImage(tmp_img, master=root)
extraref[i][j] = tk.Label(root)
extraref[i][j].img = img
extraref[i][j].config(image = extraref[i][j].img)
butts[i*8+j].config(image = extraref[i][j].img)
extraref[i][j].pack()
init()
root = tk.Tk()
frame = tk.Frame(root, width=800, height=800, background="white")
frame.pack_propagate(0)
frame.pack()
lab = tk.Label(frame)
lab.pack()
butts = list()
for i in range (8):
for j in range (8):
lab.grid(row=i, column=j)
butt = tk.Button(lab, bg=("black" if i%2 != j%2 else "white"))
#butt.config(height=5, width=8)
#butt.bind("<Enter>", on_enter)
#butt.bind("<Leave>", on_leave)
butts.append(butt)
butt.grid(row=i, column=j) #creating button grid
board = Board()
refresh(board) #places pieces on the grid
root.mainloop()
P.S:完整代码请查看pastebin,我不得不剪切一些功能才能发布它
【问题讨论】:
-
tk.Label()insideinit()将创建第一个窗口。root = tk.Tk()将创建第二个窗口。也许在root = tk.Tk()之后调用init()。 -
完美,谢谢!您能否将其发布为答案,以便我将其标记为已解决?