我的脚本似乎在启动时执行按钮及其回调,而不是按照我的想法推送。我做错了什么?
在脚本启动后,调用似乎也没有重新执行 - 当我点击它们时它们不会发送命令。
from Tkinter import *
from socket import *
host="172.25.13.10"
port=7142
#s = socket(AF_INET,SOCK_STREAM)
#s.connect((host,port))
on ='02 00 00 00 00'#\x00\x00\x02\x12\x01'
#on = "\x02\x00\x00\x00\x00\x02"
#off = "\x02\x01\x00\x00\x00\x03"
off ='02 01 00 00 00'
master = Tk()
master.attributes('-fullscreen', True)
def callback_power_on(data, host, port):
print "power on!"
#connection = socket(AF_INET,SOCK_STREAM)
connection = socket(AF_INET, SOCK_STREAM)
connection.connect((host,port))
connection.sendall(add_checksum(data))
#connection.sendall(data)
#print (sum_words(data))
connection.close()
def callback_power_off(data,host, port):
print "power off!"
connection = socket(AF_INET, SOCK_STREAM)
connection.connect((host,port))
connection.sendall(add_checksum(data))
#connection.sendall(data)
connection.close()
def add_checksum(s):
result = []
acc = 0
for hexcode in s.split():
code = int(hexcode, 16)
acc += code
result.append(chr(code))
result.append(chr(acc))
return ''.join(result)
b = Button(master, text="Power On", command=callback_power_on(on,host, port))
b.pack()
c = Button(master, text="Power Off", command=callback_power_off(off,host, port))
c.pack()
#top = Toplevel()
mainloop()
答案 0 :(得分:3)
简而言之,参数command
必须获得一个可调用的非一个不可调用的对象,如None
,如您的示例所示。
在b = Button(master, text="Power On", command=callback_power_on(on,host, port))
命令中求值为None,因为该函数没有显式返回任何值!
你可能意味着:
b = Button(master, text="Power On", command=callback_power_on)
或者如果你想将参数传递给回调函数:
b = Button(master, text="Power On", command= lambda: callback_power_on(on,host, port))
你实际上不会调用该函数,而是将其作为command
- 参数的值传递!
您可以使用:
functools.partial
与lambda