我正在嘗試制作一個按鈕來保存您的用戶名,但在您設定后就會消失。這是我的代碼:
def printValue():
User = Name.player_name.get()
label.config(text=f'Hi, {User}')
Name.button.destroy()
Name.player_name.destroy()
def Name():
label.config(text="What's your name?")
Name.player_name = Entry(root)
Name.player_name.pack(pady=15)
Name.button = Button(text="Change", command=printValue)
Name.button.pack()
uj5u.com熱心網友回復:
下面的代碼進行了一些小的更改,例如啟用更改,[Return]并且一些布局裝飾可以正常作業(也可以在 中使用未注釋的行printValue)。如果您希望[Change]按鈕和輸入區域消失,請取消注釋這兩行變成printValue函式中的注釋:
# https://stackoverflow.com/questions/72671126/tkinter-destroying-an-object-in-a-different-function-isnt-working
from tkinter import Tk, mainloop, Entry, Button, Label
root = Tk()
label = Label(root, font=('',12), padx=15, pady=5)
label.pack()
def Name():
label.config(text="What's your name?")
Name.player_name = Entry(root, font=('',12))
Name.player_name.pack(padx=15, pady=15)
Name.player_name.focus()
Name.button = Button(text="Change", command=printValue)
Name.button.pack()
def printValue(event=None):
User = Name.player_name.get()
# Name.player_name.destroy()
# Name.button.destroy()
label.config(text=f'Hi, {User}')
Name()
root.bind("<Return>", printValue)
mainloop()
順便說一句:問題中提供的代碼演示了一種有趣的方法,即通過在函式本身中設定函式屬性來使變數名稱成為全域變數。通過這種方式,可以在一個函式中分配值并在另一個函式中檢索它們,而無需傳遞回傳值或宣告全域變數。我不知道已經在 stackoverflow 上的 Python 代碼中看到過這種方法。你怎么會使用這樣的代碼?
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/492951.html
