簡體   English   中英

在 Python 的 if 語句中為 function 分配名稱

[英]Assigning a function a name in an if statement in Python

我是 python 的新手,我非常困惑。 如果有人可以幫助我將由此創建的矩形分配給名稱“Obj3”,那將非常有幫助(您可以在下面看到)。

if event.char == "c": canvas.create_rectangle(x, y, x + 100, y + 50)

這是我的程序代碼: -

app = tk.Tk()
app.title("VAB")
app.iconbitmap(r"C:\Users\shafa\OneDrive\Documents\VAB\Sprites\VAB-Icon.ico")
w, h =1200, 800
x, y = w//2, h//2


canvas = tk.Canvas(app, width = w, height = h)
canvas.pack()
Obj1 = canvas.create_rectangle(x, y, x + 100, y + 200)
points = [650, 400, 600, 330, 550, 400]
Obj2 = canvas.create_polygon(points, fill='', width = 1, outline = 'black')

def creation(event):
    if event.char == "c": canvas.create_rectangle(x, y, x + 100, y + 50) = Obj3

app.bind("<Key>", keyinput)
app.mainloop()

從這段代碼中,通過添加 = Obj3 來分配創建矩形 Obj3 的事件不起作用並導致錯誤。 我想為它分配一個名稱而不會發生該錯誤。 謝謝您閱讀此篇。

您的語法是向后的,為了分配 scope,您需要一個global聲明。

def creation(event):
    global Obj3
    if event.char == "c": Obj3  = canvas.create_rectangle(x, y, x + 100, y + 50)

不過,一般來說,全局變量不是推薦的做事方式。 您會得到意大利面條代碼,並且很難支持多線程。 最好將引用保存在本地或封裝在 class 中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM