Global/Local 在 Python2.7 中更新 Tkinter GUI 时出现命名空间问题?

Global/Local namespace issue while updating Tkinter GUI in Python2.7?

编辑: 我在 Python 2.7 中使用 Tkinter 构建了一个用户界面,我也在 concurrent.futures 的套接字处接收数据模块。现在我希望 GUI 在 sock.recv() 有新数据时 update 但这并没有发生,可能是因为全局'val1' 正在一个未来的线程(处理套接字)中更新,而不是另一个正在处理 GUI 的线程。因此,包含 val1 的 GUI 中的 Listbox 保持静态。这是一个很长的代码,所以我没有将整个代码放在这里,而是添加了一个伪代码来澄清问题。

from Tkinter import *
import concurrent.futures
....

class UserInterface(Frame):
    def __init__(self, root):
        Frame.__init__(self, root)
        self.root = root

        global var1, var2

        # Rest of the code

        self.update()
        root.mainloop() # I have to do this, otherwise the GUI doesn't show


    def update(self):
        try:
            self.var1 = var1
            self.var2 = var2

            # Inserting/displaying the latest values of var1 and var2 in Listbox defined in the constructor
            # Rest of the update function

            self.root.after(5000, update)
        except:
            pass


def conn_handler(conn, addr):
    global val1, val2
    while True:
        buff= conn.recv(2048)
        data= json.loads(buff.strip('x'))    # 'x' is the EOL character
        val1 = ''.join(data[key1]) # not exactly but something like this
        val2 = ''.join(data[key2]) # and so on

def ui_handler():
    root= Tk()
    my_gui = UserInterface(root)
    # I earlier put my_gui.root.mainloop() here but that doesn't help either


def main():
    with concurrent.futures.ThreadPoolExecutor(5) as executor:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        sock.bind((HOST, PORT))
        while True:
            sock.listen(5)
            conn, addr = sock.accept()
            future1 = executor.submit(conn_handler, conn, addr)
            future2 = executor.submit(ui_handler)
            concurrent.futures.wait([future1, future2])


if __name__=='__main__':
    val1 = {'key1':value1, 'key2':value2, 'key3':value3, 'key4':value4, 'key5':value5}
    val2 = {'key1':value1, 'key2':value2, 'key3':value3, 'key4':value4}
    main()

当我运行它的时候代码没有错误,但是它没有做我想做的,也就是说,每次有一个更新GUI接收套接字上的新数据。我的 approach/logic 有问题吗?

P.S. 我对 Python 和一般的编程还很陌生,所以请多关照!

可能不是本地或全局命名空间的问题;也可能是简单的文本框或列表框不刷新的问题。我建议在每个更新函数中,您 删除 小部件中的早期值,然后 插入 任何新值!

在你的情况下,是这样的:

self.list_box.delete(0, END)
for i in range(len(values)):
    self.list_box.insert(END, values[i])