将 self 发送到类外部的回调函数



我有类 GUI 和一个按钮,按下按钮需要激活不属于类 GUI 但需要运行一些 GUI 类成员函数的功能。 我该怎么做? 这是我的按钮创建:

tk.Button(self.top_frame, text="connect to server", var=self, command=connect_to_server)

这是函数:

def connect_to_server(gui):
res = False
try:
# Create a socket object
# write_to_log("Socket successfully created")
ans = s.connect((SERVER_IP, PORT))
if ans is None:
gui.write_to_log('connection to server establish')
gui.connection.configure(state="disable")
res = True
tk.Label(gui.top_frame, text="Connected", bg="green").grid(row=0, column=1)
gui.chk_smds_state.set(tk.TRUE)
else:
gui.write_to_log('connection failed')
return res
message = receive(s)
# write_to_log(str(message, 'ascii'))
gui.write_to_log(message)
res = res
except socket.error as err:
message = f"socket creation failed with error %s" % err
gui.connection.configure(bg='red')
gui.write_to_log(message)
return res
def main():
root = Tk()
my_gui = MyFirstGUI(root)
root.mainloop()
if __name__ == "__main__":
main()

编辑aaded 主要功能以理解 scop

这是您正在寻找的内容的基本示例。按下按钮时,它会激活在类外部定义的功能,并将文本设置为标签

from Tkinter import Tk, Label, Button
def set_label_text():
my_gui.label_to_set.config(text="New text")
class MyFirstGUI:
def __init__(self, master):
self.button = Button(master, text="Click me", command=set_label_text)
self.button.pack()
self.label_to_set = Label(master)
self.label_to_set.pack()
root = Tk()
my_gui = MyFirstGUI(root)
root.mainloop()

最新更新