![](/img/trans.png)
[英]Is there an alternative for '<Button-1>' with bind() function in Tkinter ?- Python
[英]Tkinter - How to bind <Button-1> and call a function
我試圖讓以下代碼在事件調用 function 以清除輸入框的情況下工作。 有人可以告訴我我做錯了什么。 我對Tkinter不太熟悉。
import tkinter as tk
from tkinter import *
class Example(Frame):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.master.title("Create Trusted Facts")
self.pack(fill=BOTH, expand=True)
frame2 = Frame(self)
frame2.pack(fill=X)
reqSumLbl = Label(frame2, text="Request Summary", width=22)
reqSumLbl.pack(side='left', padx=5, pady=5)
reqSumBox = Entry(frame2, width=100, bg="White", fg="lightgrey", borderwidth=1)
reqSumBox.insert(0, "Enter the Request Summary here")
reqSumBox.pack(fill=X, padx=50, pady=5, expand=True)
reqSumBox.bind("<Button-1>", self.clear_reqSumBox)
def clear_reqSumBox(self, reqSumBox):
reqSumBox.delete(0, END)
reqSumBox.config(fg="black")
global SummaryText
SummaryText = reqSumBox.get()
def main():
root = Tk()
root.geometry("500x550+350+50")
app = Example()
root.mainloop()
if __name__ == '__main__':
main()
reqSumBox.bind("<Button-1>", self.clear_reqSumBox)
將任何事件綁定到 function 時,它會自動需要一個名為 event 的參數,有兩種方法可以修復您的代碼。
1.
reqSumBox.bind("<Button-1>", lambda event: self.clear_reqSumBox)
制作 lambda function 接受事件並調用 function。
2.
def reqSumBox(self, reqSumBox, event=None)
在 reqSumBox function 中添加可選事件參數。
我個人使用第一個。
首先,為什么在 Python 腳本的開頭有兩個導入,它們都是同一個庫,選擇一個不正確。
關於您的問題,它失敗了,因為您沒有提供點擊的 object,它為您提供了作為綁定 function 發生的事件的第一個參數。
我建議你讓你的 object 成為你當前工作的 class (類示例)的一部分,就像這樣:
import tkinter as tk
from tkinter import *
class Example(Frame):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.master.title("Create Trusted Facts")
self.pack(fill=BOTH, expand=True)
frame2 = Frame(self)
frame2.pack(fill=X)
reqSumLbl = Label(frame2, text="Request Summary", width=22)
reqSumLbl.pack(side='left', padx=5, pady=5)
# Check my changes here.
self.reqSumBox = Entry(frame2, width=100, bg="White", fg="lightgrey", borderwidth=1)
self.reqSumBox.insert(0, "Enter the Request Summary here")
self.reqSumBox.pack(fill=X, padx=50, pady=5, expand=True)
self.reqSumBox.bind("<Button-1>", self.clear_reqSumBox)
# Changed the argument name to "event".
def clear_reqSumBox(self, event):
self.reqSumBox.delete(0, END)
self.reqSumBox.config(fg="black")
def main():
root = Tk()
root.geometry("500x550+350+50")
app = Example()
root.mainloop()
if __name__ == '__main__':
main()
檢查我在哪里評論和分析這段代碼。
bind()
的回調需要一個參數,即事件 object。 所以修改回調function定義如下:
def clear_reqSumBox(self, event):
# get the widget triggering this event
reqSumBox = event.widget
reqSumBox.delete(0, END)
reqSumBox.config(fg="black")
# after that reqSumBox.get() will return empty string
global SummaryText
# SummaryText = "" will have same result of below line
SummaryText = reqSumBox.get()
但是,只要您單擊該條目,該條目就會被清除。 真的是你想要的嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.