![](/img/trans.png)
[英]tkinter: tag_bind in for-loop only passes the last tag as a parameter in the lambda event function
[英]Lambda function in for loop to bind keywords in tkinter
我對 Python 和 tkinter 非常陌生。 我正在使用 tkinter 開發鍵盤。 我創建了一個文本框,我正在嘗試將鍵綁定到它,以便用戶可以使用鍵盤進行輸入。 我想在按下一個鍵時打印不同的鍵。 例如,我想在按下“p”時打印 P,當按下“a”時打印 A。 我知道我可以手動輸入每個鍵並添加一個 function 來打印所需的值,但這會很耗時,所以我決定使用字典。
下面是這個的代碼。
def print_letter(letter):
if letter == "backspace":
text.configure(state="normal")
value = text.get("1.0", "end")
text.delete("1.0", "end")
text.insert("1.0", value[:-2])
text.configure(state="disabled")
else:
text.configure(state="normal")
text.insert("end", letter)
text.configure(state="disabled")
letters = {
'a': 'A',
'b': 'B',
'c': 'C',
'd': 'D',
'e': 'E',
}
root = tk.Tk()
root.geometry("800x415")
root.resizable(False, False)
text = tk.Text(text_frame, width=97, height=15)
text.configure(state="disabled")
text.grid(row=0, column=0, sticky="EW")
text.focus_set()
for key, value in letters.items():
text.bind(key, lambda value: print_letter(letters.get(key)))
但只有字典中的最后一個值綁定到我按下的任何鍵。 我在 SO 上看到了一些帖子,他們都建議了以下選項:
以上所有給了我相同的結果。
任何幫助表示贊賞。
我個人的偏好是使用functools.partial
而不是lambda
,因為它會凍結 arguments。 這是一個在實踐中的例子。
import tkinter as tk
from functools import partial
# here we add an *args argument
# since tkinter will also send the keystroke
# as an argument
def print_letter(letter, *args):
if letter == "backspace":
text.configure(state="normal")
value = text.get("1.0", "end")
text.delete("1.0", "end")
text.insert("1.0", value[:-2])
text.configure(state="disabled")
else:
text.configure(state="normal")
text.insert("end", letter)
text.configure(state="disabled")
letters = {
'a': 'A',
'b': 'B',
'c': 'C',
'd': 'D',
'e': 'E',
}
root = tk.Tk()
root.geometry("800x415")
root.resizable(False, False)
text = tk.Text(root, width=97, height=15)
text.configure(state="disabled")
text.grid(row=0, column=0, sticky="EW")
text.focus_set()
for key, value in letters.items():
# partial takes unlimited args.
# The first being the function name
# and subsequent ones being the arguments
text.bind(key, partial(print_letter, value))
root.mainloop()
如果我正確理解了您的問題,那么您需要某事。 像這樣:
l = []
for _ in range(10):
l.append(lambda v=_: print(v))
希望這會有所幫助!
它會起作用
l = []
對於范圍內的 _ (10): l.append(lambda v=_: print(v))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.