[英]Can't type text into tkinter entry widget (python)
我正在使用 tkinter 來獲取要打開的文件路徑,然后問用戶兩個問題,通過文本輸入小部件命名,並通過一些單選按鈕進行課程。 我從該線程的答案中獲得的單選按鈕的代碼效果很好: 如何使用 tkInter 顯示一個詢問用戶多項選擇問題的對話框? 然后我決定添加 Entry 小部件以獲得名稱問題的答案並且一直在苦苦掙扎。 我已經讓它工作了,但是有錯誤:
我不知道從這里到 go 的位置。 我試過使用e1.focus()
但沒有任何區別。 我已經嘗試在打開文件對話框之前運行問題 window 但這真的很困惑。 我已經嘗試注釋掉清除條目 function 以防萬一導致問題但行為基本相同。 編輯:我正在使用來自 Anaconda 3 的 Spyder 作為我的 IDE,我想知道這是否會導致問題 1,因為 @acw1668 無法復制它。
這是我的代碼:
root=tk.Tk()
csvfp=tk.filedialog.askopenfilename()
SName, ProgSel=ask_multiple_choice_question(root, LPrograms)
def ask_multiple_choice_question(root, options):
#https://stackoverflow.com/questions/42581016/how-do-i-display-a-dialog-that-asks-the-user-multi-choice-question-using-tkinter
#Define a function to clear the contents of the textbox when it is clicked
def click(event):
e1.configure(state=tk.NORMAL)
e1.delete(0,tk.END)
e1.unbind('<Button-1>',clicked)
#checks entries are valid when submit button is clicked, then closes window
def validate():
if v.get() == 0 or v2.get() == "" or v2.get()==starttext:
return None
root.destroy()
frame1=Frame(root)
frame1.pack(padx=20,pady=10)
frame2=Frame(root)
frame2.pack()
frame3=Frame(root)
frame3.pack(pady=10)
Label(frame1, text="Student name?").pack()
v2=tk.StringVar()
e1 = Entry(frame1, width=30, textvariable=v2)
starttext="Surname, Firstname (ID)"
e1.insert(0, starttext)
e1.pack()
#bind e1 with mouse button to clear contents on click
clicked=e1.bind('<Button-1>',click)
Label(frame2, text="Program?").pack()
v = IntVar()
for i, option in enumerate(options):
Radiobutton(frame2, text=option, variable=v, value=i).pack(anchor="w")
Button(frame3, text="Submit", command=validate).pack()
root.mainloop()
return v2.get(), options[v.get()]
感謝您提供任何線索!
對於問題 #1,您需要在主 window 准備好並可見后顯示文件對話框。 您可以在root = tk.Tk()
root.wait_visibility()
() :
...
root = tk.Tk()
root.wait_visibility()
...
對於問題 #2,由於第一個單選按鈕的value
選項為 0,並且其 tkinter 變量v
的初始值默認為 0,因此將選擇第一個單選按鈕。 將v
的初始值設置為 -1 將修復它:
...
def validate():
# check -1 instead of 0
if v.get() == -1 or v2.get() == "" or v2.get() == starttext:
return None
root.destroy()
...
v = tk.IntVar(value=-1)
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.