問題描述
我有一個具有 Entry
小部件和提交 Button
的 GUI.
I have a GUI that has Entry
widget and a submit Button
.
我基本上是在嘗試使用 get()
并打印 Entry
小部件內的值.我想通過單擊 submit Button
或按鍵盤上的 enter 或 return 來執行此操作.
I am basically trying to use get()
and print the values that are inside the Entry
widget. I wanted to do this by clicking the submit Button
or by pressing enter or return on keyboard.
我嘗試將 "<Return>"
事件與我按下提交按鈕時調用的相同函數綁定:
I tried to bind the "<Return>"
event with the same function that is called when I press the submit Button:
self.bind("<Return>", self.enterSubmit)
但我得到一個錯誤:
需要 2 個參數
但是 self.enterSubmit
函數只接受一個,因為 Button
的 command
選項只需要一個.
But self.enterSubmit
function only accepts one, since for the command
option of the Button
is required just one.
為了解決這個問題,我嘗試創建 2 個功能相同的函數,它們只是具有不同數量的參數.
To solve this, I tried to create 2 functions with identical functionalities, they just have different number of arguments.
有沒有更有效的方法來解決這個問題?
Is there a more efficient way of solving this?
推薦答案
您可以創建一個接受任意數量參數的函數,如下所示:
You can create a function that takes any number of arguments like this:
def clickOrEnterSubmit(self, *args):
#code goes here
這稱為任意參數列表.調用者可以隨意傳入任意數量的參數,并且它們都將被打包到 args
元組中.Enter 綁定可以傳入它的 1 個 event
對象,而 click 命令可以不傳入任何參數.
This is called an arbitrary argument list. The caller is free to pass in as many arguments as they wish, and they will all be packed into the args
tuple. The Enter binding may pass in its 1 event
object, and the click command may pass in no arguments.
這是一個最小的 Tkinter 示例:
Here is a minimal Tkinter example:
from tkinter import *
def on_click(*args):
print("frob called with {} arguments".format(len(args)))
root = Tk()
root.bind("<Return>", on_click)
b = Button(root, text="Click Me", command=on_click)
b.pack()
root.mainloop()
結果,按Enter
并點擊按鈕后:
Result, after pressing Enter
and clicking the button:
frob called with 1 arguments
frob called with 0 arguments
如果您不愿意更改回調函數的簽名,可以將要綁定的函數包裝在 lambda
表達式中,并丟棄未使用的變量:
If you're unwilling to change the signature of the callback function, you can wrap the function you want to bind in a lambda
expression, and discard the unused variable:
from tkinter import *
def on_click():
print("on_click was called!")
root = Tk()
# The callback will pass in the Event variable,
# but we won't send it to `on_click`
root.bind("<Return>", lambda event: on_click())
b = Button(root, text="Click Me", command=frob)
b.pack()
root.mainloop()
這篇關于單擊按鈕并按回車時調用相同的函數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!