这是Tkinter游戏代码的一部分 随机和tkinter模块已导入。 我的问题是-
1。 Struct类仅已初始化但尚未定义,仅通过传递即可使用。
def run(rows, cols):
# create the root and the canvas
global canvas
root = Tk()
margin = 5
cellSize = 15
canvasWidth = 2*margin + cols*cellSize
canvasHeight = 2*margin + rows*cellSize+100
canvas = Canvas(root, width=canvasWidth, height=canvasHeight)
canvas.pack()
# Store canvas in root and in canvas itself for callbacks
root.canvas = canvas.canvas = canvas
# Set up canvas data and call init
class Struct: pass
canvas.data = Struct()
canvas.data.margin = margin
canvas.data.cellSize = cellSize
canvas.data.canvasWidth = canvasWidth
canvas.data.canvasHeight = canvasHeight
canvas.data.rows = rows
canvas.data.cols = cols
canvas.data.canvasWidth = canvasWidth
canvas.data.canvasHeight = canvasHeight
canvas.data.player1Score = 0
canvas.data.player2Score = 0
canvas.data.inGame = False
init()
# set up events
root.bind("<Key>", keyPressed)
timerFired()
# and launch the app
root.mainloop() # This call BLOCKS (so your program waits until you close the window!)
run(40,40)
2。 这行代码中也发生了什么:
root.canvas = canvas.canvas = canvas
class Struct: pass
canvas.data = Struct()
答案 0 :(得分:0)
问题:结构类尚未定义吗?
您错了,class Struct
已定义。
这行定义了一个有效的对象:
class Struct: pass
以下两个示例是等效的!
空对象Struct
成为canvas
属性,然后使用属性扩展该对象。
margin = 5
# Define the object
class Struct: pass
# Instantiate the object `Struct`
# Assign the reference to the object `Struct` to the attribute `.data`
canvas.data = Struct()
# Assing the value `margin` to the attribute `.margin` of the object `Struct`
canvas.data.margin = margin
# Access the attribute `.margin` in the object `Struct`
print(canvas.data.margin)
# >>> 5
对象Struct
使用预定义的class Struct.__init__
margin = 5
# Define the object
class Struct:
def __init__(self, margin):
self.margin = margin
# Instantiate the object `Struct`
# Pass the value `margin` to it
# Assign the reference to the object `Struct` to the attribute `.data`
canvas.data = Struct(margin)
# Access the attribute `.margin` in the object `Struct`
print(canvas.data.margin)
# >>> 5