我正在處理 tkinter 中的輸入框。它應該在(在條目中)取一個值,一旦按下“確定”按鈕,該值將被分配給一個變數。關閉 tkinter 視窗后,將列印變數。這是代碼:
import tkinter as tk
root = tk.Tk()
root.title("Input")
root.geometry("400x200")
a = ""
entry1 = tk.Entry(root)
entry1.pack()
def entry1Input():
a = entry1.get()
print(a)
okay = tk.Button(root,text = "Okay", command = entry1Input())
okay.pack()
root.mainloop()
print("A: " a)
問題是當我關閉視窗時,該值與我第一次定義它時的值相同。我有一段時間沒有撰寫 python 代碼了,所以這可能是一個簡單的錯誤。你能告訴我錯誤是什么嗎?
uj5u.com熱心網友回復:
你有兩個問題。首先,您沒有在此處傳遞函式物件:
okay = tk.Button(root,text = "Okay", command = entry1Input())
相反,您正在呼叫該函式。該函式回傳None,這就是您發送給command. 你需要:
okay = tk.Button(root,text = "Okay", command = entry1Input)
然后,a您的函式中的 是該函式的本地函式,并在函式結束時消失。你需要:
def entry1Input():
global a
我真誠地希望你不要a在這里使用你的變數名。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/477334.html
