簡體   English   中英

Tkinter - 在函數中綁定事件處理

[英]Tkinter - Bind event handling in function

我正在嘗試實現一個功能,其中 tk-Button xor Keyboard Button Press 正在運行相同的功能。

這是一個代碼示例:

from tkinter import *


root = Tk()
root.geometry("800x600")
root.title("Event Testing")

def on_closing():
    root.destroy()

root_button = Button(root, text="Exit", command=on_closing)
root_button.place(x=400, y=300, anchor=CENTER)

# root.bind("<Escape>", on_closing)

root.mainloop()

當我綁定<Escape>按鈕並按下它時出現錯誤:

TypeError: on_closing() missing 1 required positional argument: 'event'

如果我將event變量放入def on_closing(event)之類的函數中,則<Escape>按鈕可以工作,但 tk-Button 會再次引發相同的錯誤。

有沒有更好的選擇,然后將<Button-1>綁定到 tk-Button 或創建一個帶有event變量的函數和一個沒有事件變量的函數並將其拆分。

編輯:

我認為我發現了一些丑陋但有效的解決方法。

root_button = Button(root, text="Exit", command=lambda: on_closing(""))

如果還有更好的方法,我想聽聽;)。

這是一個可行的解決方案,我對 root.bind() 使用了 lambda 函數而不是root.bind() on_closing()函數。 另一種選擇可能是全部在 OOP 中編程。

from tkinter import *


root = Tk()
root.geometry("800x600")
root.title("Event Testing")

def on_closing():
    root.destroy()

root_button = Button(root, text="Exit", command=on_closing)
root_button.place(x=400, y=300, anchor=CENTER)

root.bind("<Escape>", lambda x: root.destroy())

root.mainloop()

編輯:

好的,再試一次。 使用event=None ,因此事件被定義為默認無。 由於定義,您不會得到錯誤,它是相同的功能。

from tkinter import *

def on_closing(event=None):
    root.destroy()

root = Tk()
root.geometry("800x600")
root.title("Event Testing")
root.bind("<Escape>", on_closing)
    
root_button = Button(root, text="Exit", command=on_closing)
root_button.place(x=400, y=300, anchor=CENTER)

root.mainloop()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM