4 回答

TA貢獻1816條經驗 獲得超4個贊
直接的方法是使用winfo_exists():
root.option_wnd = None # Init value
def press_enter(event):
#messagebox.showinfo("Inside")
selected=trv.focus()
print(trv.item(selected))
print(str((event.keysym)))
if str((event.keysym))=='Return':
if root.option_wnd and root.option_wnd.winfo_exists():
root.option_wnd.lift() # make this window on the top.
else: # create this window
root.option_wnd = tk.Toplevel(root)
.....
但我認為你不需要每次用戶輸入時都創建這個窗口。Enter在開始時創建它,只需在用戶輸入時顯示它Enter
例如:
root = tk.Tk()
option_wnd = tk.Toplevel()
option_wnd.wm_protocol("WM_DELETE_WINDOW", option_wnd.withdraw) # when user try to close this window, hide it instead of destroy it
.....
option_wnd.withdraw() # hide this window
def press_enter(event):
#messagebox.showinfo("Inside")
selected=trv.focus()
print(trv.item(selected))
print(str((event.keysym)))
if str((event.keysym))=='Return':
option_wnd.deiconify() # show it.

TA貢獻2041條經驗 獲得超4個贊
我能想到的一個選項是像這樣綁定選項窗口:
option_wnd.bind('<Return>', lambda e: option_wnd.close()) # or withdraw() or quit() ?
將選項窗口綁定到按下 Enter 鍵時它會關閉(盡管我不知道上述函數的差異(有,所以你應該查找)),但是如果你想使用Enter
(返回)輸入值,這可能會妨礙你鍵,因為它將關閉窗口。另一個選項是將選項窗口綁定到此事件:
option_wnd.bind('<FocusOut>', lambda e: option_wnd.close())
這是當窗口不再受到關注時,因此如果您按 Enter 鍵,它將打開一個新窗口,但仍然打賭舊窗口應該關閉。您也可以嘗試用某些東西進行一些邏輯編程,例如當輸入按下“打開”模式時,再次按下它不會打開窗口,而當您關閉現有窗口時,它將再次允許這種情況。

TA貢獻1871條經驗 獲得超8個贊
def press_enter(event):
#messagebox.showinfo("Inside")
root.deiconify ()
selected=trv.focus()
print(trv.item(selected))
print(str((event.keysym)))
if str((event.keysym))=='Return':
option_wnd=Toplevel(root)
option_wnd.geometry('200x200')
option_wnd.title('Option Window')
option_wnd.grab_set()
#option_wnd.pack()

TA貢獻1876條經驗 獲得超5個贊
如果您不使用類,您可以執行以下操作:
options_displayed = False #global
def option_closed(w):
global options_displayed
w.destroy() #close the actual window
options_displayed = False # log the fact it is now close
def press_enter(event):
global options_displayed # reference global variable
#messagebox.showinfo("Inside")
selected=trv.focus()
print(trv.item(selected))
print(str((event.keysym)))
if str((event.keysym))=='Return' and not options_displayed:
option_wnd=Toplevel(root)
option_wnd.geometry('200x200')
option_wnd.title('Option Window')
option_wnd.grab_set()
option_wnd.grab_set()
option_wnd.protocol("WM_DELETE_WINDOW", lambda w= option_wnd :option_closed(w))
添加回答
舉報