我不知道为什么这些子类会继续创建新的tkinter画布

问题描述 投票:0回答:1

我能够用更小的50行代码重新创建问题。这就是为什么您可能会看到参数和参数似乎“毫无用处”的原因。

[程序首先要做的是创建一个主窗口和游戏板对象,它是tk.Canvas的子类。然后,对象为每个120x120正方形创建8行和8行,并具有交替的颜色。

然后,我创建游戏片段(通常会在for循环中完成,但是这个破例仅创建了两个片段),分别为它们提供了60x60和60x120的展示位置。

最后,我用一个简单的退出按钮和mainloop函数将其包装起来。


每次尝试在板上放置图像项时,我的代码似乎都会在GameBoard上绘制新的画布。

现在,我相信,此错误源于GameBoard类,特别是它从基类中调用__init__方法的地方。

我已经尝试在所有不同的地方工作和重做,以使每种self方法都认为可能有所帮助,但无济于事。

但是,如果我注释掉创建车队和当铺的两行,则该面板看起来就像正常一样。因此,我知道必须是直接由碎片引起的。

所以,这是我尝试下棋的尝试。请记住,它还远未完成,下面的代码是我代码的摘录,但仅仅是为了显示错误而已。如果您看到任何与我的实际问题无关的

耀眼

问题,请知道我正在尽最大努力避免重复自己,并遵循pip8准则。因此,任何有关清洁度或整体功能的投入将不胜感激。


正如quamrana在评论中指出的:我之所以从GameBoard继承GamePiece的原因是[[特定地
,因为我想

not

不必担心更改图像的背景以匹配颜色。该图像所在的空间。import tkinter as tk from PIL import ImageTk, Image class GameBoard(tk.Canvas): def __init__(self, parent): self.color = "" #where I believe my error comes from tk.Canvas.__init__(self, parent, height=960, width=960) self.grid() #spaces created here by rows snd columns def create_spaces(self): x1, y1, x2, y2 = 0, -120, 120, 0 for _row in range(8): x1, x2 = 0, 120 y1 += 120 y2 += 120 self.alternate_colors() for _column in range(8): self.create_rectangle(x1, y1, x2, y2, fill=self.color) x1 += 120 x2 += 120 self.alternate_colors() #each space created alternates between the two colors here def alternate_colors(self): if self.color == "green": self.color = "pink" else: self.color = "green" class GamePiece(GameBoard): def __init__(self, parent, xPOS, yPOS, photo_file): GameBoard.__init__(self, parent) self.photo1 = Image.open(photo_file) self.photo2 = ImageTk.PhotoImage(self.photo1) self.create_image(xPOS, yPOS, image=self.photo2) self.grid() #main window and gameboard is created here window = tk.Tk() gameboard = GameBoard(window) gameboard.create_spaces() #all pieces will eventually be created here using for loops gamepiece1 = GamePiece(gameboard, 60, 60, "black_rook.png") gamepiece2 = GamePiece(gameboard, 60, 120, "black_pawn.png") #quit button and mainloop tk.Button(window, text="Quit", command=quit, bd=5).grid(pady=40) window.mainloop() 我能够用更小的50行代码重新创建问题。这就是为什么您可能会看到参数和参数似乎“毫无用处”的原因。程序首先要做的是创建一个主...
python class canvas tkinter init
1个回答
0
投票
是a超类。如果您的GamePiece是从GameBoard继承的,则GamePiece

© www.soinside.com 2019 - 2024. All rights reserved.