4 回答

TA貢獻(xiàn)1816條經(jīng)驗(yàn) 獲得超4個(gè)贊
直接的方法是使用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)
.....
但我認(rèn)為你不需要每次用戶輸入時(shí)都創(chuàng)建這個(gè)窗口。Enter在開始時(shí)創(chuàng)建它,只需在用戶輸入時(shí)顯示它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貢獻(xiàn)2041條經(jīng)驗(yàn) 獲得超4個(gè)贊
我能想到的一個(gè)選項(xiàng)是像這樣綁定選項(xiàng)窗口:
option_wnd.bind('<Return>', lambda e: option_wnd.close()) # or withdraw() or quit() ?
將選項(xiàng)窗口綁定到按下 Enter 鍵時(shí)它會(huì)關(guān)閉(盡管我不知道上述函數(shù)的差異(有,所以你應(yīng)該查找)),但是如果你想使用Enter
(返回)輸入值,這可能會(huì)妨礙你鍵,因?yàn)樗鼘㈥P(guān)閉窗口。另一個(gè)選項(xiàng)是將選項(xiàng)窗口綁定到此事件:
option_wnd.bind('<FocusOut>', lambda e: option_wnd.close())
這是當(dāng)窗口不再受到關(guān)注時(shí),因此如果您按 Enter 鍵,它將打開一個(gè)新窗口,但仍然打賭舊窗口應(yīng)該關(guān)閉。您也可以嘗試用某些東西進(jìn)行一些邏輯編程,例如當(dāng)輸入按下“打開”模式時(shí),再次按下它不會(huì)打開窗口,而當(dāng)您關(guān)閉現(xiàn)有窗口時(shí),它將再次允許這種情況。

TA貢獻(xiàn)1871條經(jīng)驗(yàn) 獲得超8個(gè)贊
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貢獻(xiàn)1876條經(jīng)驗(yàn) 獲得超5個(gè)贊
如果您不使用類,您可以執(zhí)行以下操作:
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))
添加回答
舉報(bào)