tkinter wait_variable不会回调到intvar更改

时间:2019-10-02 13:39:36

标签: python tkinter

我对“高级编程”和GUI非常陌生,因此,这个问题无疑很容易解决。

我有一个用Tkinter制作的GUI,以及一个在两个列表框上显示两个数据库之间差异的窗口:一个是最新的,另一个不是。提示用户选择哪个条目是最新的。

enter image description here

我的问题是,直到用户没有单击任一“接受”按钮,程序都应等待响应。而且我不知道该怎么做。这是一些代码:

class Page_one(object):
    selected_entries = []   

    def update(self, db_entries, sm_entries):
        non_matches = []

        for db_ent in db_entries:
            for sm_ent in sm_entries:
                if db_ent.name_equals(sm_ent):
                    # name_equals() is a function that compares
                    # name, surname and age of the self.entry with the
                    # target entry and returns True when they differ only in age

                    # if they don't match (i.e. name_equals returns True) i'll add
                    # these two entries to a list and will later show them to the user
                    non_matches.append( (db_ent, sm_ent) )
                    break

        for x, y in non_matches:
            # inserts in the 'l-eft' or 'r-ight' listbox the entry
            self.listbox_insert('l', x)
            self.listbox_insert('r', y)

            # here I want the program to wait for user input and
            # set z = x or y depending on user's choice
            z = user_selected_entry()
            self.selected_entries.append(z)
            send_to_final_db(self.selected_entries)

我希望代码清晰,我已经省略了许多GUI定义和辅助功能(例如listbox_insert('l', x))。

编辑

这是我一直在为Buttons使用的代码,

...
self.root = Tk()
self.flag = IntVar() # variable that should respond to change
self.btn_accept_left = Button(self.root, text="Accept this", command=lambda: self.flag.set(1))
self.btn_accept_right = Button(self.root, text="Accept this", command=lambda: self.flag.set(2))
self.btn_accept_left.grid(row=2, column=0)
self.btn_accept_right.grid(row=2, column=1)

    ... # until we get to the same point

    for x, y in non_matches:
        # inserts in the 'l-eft' or 'r-ight' listbox the entry
        self.listbox_insert('l', x)
        self.listbox_insert('r', y)

        # here I want the program to wait for user input and
        # set z = x or y depending on user's choice
        self.root.wait_variable(self.flag)

        print('Will it ever move?') # <--- NEVER REACHED

        # flag changed, we continue
        z = user_selected_entry()
        self.selected_entries.append(z)
        send_to_final_db(self.selected_entries)

我已经尝试了将不同版本的事件绑定到Button,但是没有一个起作用。执行永远不会到达指令(之后?)self.root.wait_variable(self.flag)

1 个答案:

答案 0 :(得分:0)

由于我是新来的,所以我无法发表评论, 这是一个事件任务。您等待事件发生并对其进行绑定。

请参阅 https://www.python-course.eu/tkinter_events_binds.php