2

My script seems to execute the buttons and their callbacks on startup, not as when pushed as I would think. what am i doing wrong?

The calls also don't seem to re-execute after the script has started--they aren't sending the commands when I'm clicking them.

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()
inbinder
  • 692
  • 4
  • 11
  • 28

1 Answers1

4

In short the argument command must get a callable and NOT a non-callable object like None, as in your example.

In b = Button(master, text="Power On", command=callback_power_on(on,host, port)) command evaluates to None, because the function doesn't explicitly return any value!

You probably meant:

b = Button(master, text="Power On", command=callback_power_on)

or if you want to pass paramters to the callback function:

b = Button(master, text="Power On", command= lambda: callback_power_on(on,host, port))

You actually DO NOT call the function, but pass it as the value of the command-argument!

You may eiter use:

  • a normal function
  • encapsulate a function-call into a lambda function
  • use functools.partial with the same result as with a lambda
  • create a callable-object
  • another factory-function/-object
Don Question
  • 11,227
  • 5
  • 36
  • 54