![](/img/trans.png)
[英]How can I use the array of one function into another function in python tkinter?
[英]If I created widgets in one function, how can I access them in another function using Python Tkinter?
這是我第一個使用 Tkinter 的項目,所以如果問題很容易解決,請原諒。 根據用戶從下拉列表中選擇的選項,我調用 function 來創建某些小部件(例如條目)並將其放置在框架上。 然后,當按下另一個按鈕時,我想訪問此條目中的文本。 但是,這似乎給了我錯誤(說小部件未定義),因為我想訪問我在調用 function 時創建的小部件。
我看到的一個明顯的解決方案是創建我想在 function 之外使用的所有可能的小部件,並且僅在調用 function 時放置它們。 這似乎很草率,並產生了更多問題。 還有其他修復嗎?
提前致謝!
這是 function,我在其中創建小部件並將其放置在框架上。
def loadBook():
print("book is loaded")
#Authors
labelAuth1 = tk.Label(frame, text="Author 1 Name:")
entryAuth1 = tk.Entry(frame)
labelAuth1.place(relwidth=0.23, relheight=0.08, rely=0.1)
entryAuth1.place(relheight=0.08, relwidth=0.18, relx=0.3, rely=0.1)
這是 function 的片段,它使用我在上面創建的條目小部件的輸入:
def isBook():
if len(entryAuthSur1.get())==0:
pass
else:
bookString = ""
bookString += entryAuthSur1.get()
當第二個 function 執行時,我收到一個運行時錯誤,即entryAuthSur1
未定義。
函數內部的所有變量都是局部的。 這意味着它在 function 調用結束后被刪除。 由於您的變量( entryAuth1
)不是全局變量,因此它僅存在於 function 中,並且在loadBook
function 結束時被刪除。 這是工作代碼:
import tkinter as tk
# Making a window for the widgets
root = tk.Tk()
def loadBook():
global entryAuth1 # make the entry global so all functions can access it
print("book is loaded")
#Authors
labelAuth1 = tk.Label(root, text="Author 1 Name:")
entryAuth1 = tk.Entry(root)
# I will check if the user presses the enter key to run the second function
entryAuth1.bind("<Return>", lambda e: isBook())
labelAuth1.pack()
entryAuth1.pack()
def isBook():
global entryAuth1 # make the entry global so all functions can access it
# Here you had `entryAuthSur1` but I guess it is the same as `entryAuth1`
if len(entryAuth1.get())==0:
pass
else:
bookString = ""
bookString += entryAuth1.get()
print(bookString) # I am going to print the result to the screen
# Call the first function
loadBook()
root.mainloop()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.