[英]How to set Entry.get as an argument of a command function with lambda in python Tkinter
我有一個具有輸入字段和按鈕的應用程序:
from subprocess import *
from Tkinter import *
def remoteFunc(hostname):
command = 'mstsc -v {}'.format(hostname)
runCommand = call(command, shell = True)
return
app = Tk()
app.title('My App')
app.geometry('200x50+200+50')
remoteEntry = Entry(app)
remoteEntry.grid()
remoteCommand = lambda x: remoteFunc(remoteEntry.get()) #First Option
remoteCommand = lambda: remoteFunc(remoteEntry.get()) #Second Option
remoteButton = Button(app, text = 'Remote', command = remoteCommand)
remoteButton.grid()
app.bind('<Return>', remoteCommand)
app.mainloop()
我希望當我在輸入字段中插入IP /計算機名稱時,它將作為參數發送給按鈕命令,因此當我按Return或按按鈕時,它將使用該名稱/ IP遠程計算機。
當我使用第一個選項執行此代碼(查看代碼)時,它僅在按回車鍵時有效,如果按按鈕,則為錯誤:
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 1532, in __call__
return self.func(*args)
TypeError: <lambda>() takes exactly 1 argument (0 given)
如果僅在嘗試按按鈕時嘗試remoteCommand的第二個選項,但它有效,但是如果按Return鍵,則會出現此錯誤:
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 1532, in __call__
return self.func(*args)
TypeError: <lambda>() takes no arguments (1 given)
兩者之間的唯一區別是lambda是否獲得參數。
我認為最好的解決方案是不使用lambda。 IMO,應避免使用lambda,除非它確實是解決問題的最佳解決方案,例如何時需要創建閉合。
由於您希望通過返回鍵上的綁定以及單擊按鈕來調用相同的函數,因此編寫一個可以選擇接受事件的函數,然后將其忽略:
例如:
def runRemoteFunc(event=None):
hostname = remoteEntry.get()
remoteFunc(hostname)
...
remoteButton = Button(..., command = remoteFunc)
...
app.bind('<Return>', remoteCommand)
命令不獲取參數。 事件處理程序將事件作為參數。 要同時使用函數,請使用默認參數。
def remote(event=None):
remoteFunc(remoteEntry.get())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.