简体   繁体   中英

Updating Tkinter label from a StringVar happens on a delay

I have a tkinter label object which is bound to a tkinter StringVar, which should in principle cause it to update when the StringVar is changed. Here is the declaration:

self.db_info_string = tk.StringVar()
self.db_info_string.set('Number of events: ' +str(len(self.eventsdb_subset)))
self.db_info_display = tk.Label(parent, textvariable=self.db_info_string)

Elsewhere in my GUI, I have a button, which when pressed calls this function:

def filter_db(self):
    filterstring = self.filter_entry.get()
    print filterstring
    eventsdb_subset = self.eventsdb_subset
    self.eventsdb_subset = sqldf('SELECT * from eventsdb_subset WHERE %s' % filterstring,locals())
    self.db_info_string.set('Number of events: ' +str(len(eventsdb_subset)))

(I'm aware of the problems using raw input in a DB like that - this is just for testing purposes at the moment, to get the hang of GUI programming, and will be sanitized before it sees the light of day)

You can see that the value of the StringVar is changed in this function call. However, the Label text is not updated until the second call to this function - ie, the label text lags the actual value it should be displaying by one call to this function.

Is there any way to force the Label to update in filter_db()?

eventsdb_subset = self.eventsdb_subset
self.eventsdb_subset = sqldf('SELECT * from eventsdb_subset WHERE %s' % filterstring,locals())
self.db_info_string.set('Number of events: ' +str(len(eventsdb_subset)))

eventsdb_subset and self.eventsdb_subset are independent variables. Assigning to one won't change the value of the other one.

On the third line, eventsdb_subset still has the value that it had before you ran self.eventsdb_subset = sqldf(...) . In other words, it's always going to lag one select operation behind.

Update the StringVar using the value of self.eventsdb_subset instead of eventsdb_subset .

eventsdb_subset = self.eventsdb_subset
self.eventsdb_subset = sqldf('SELECT * from eventsdb_subset WHERE %s' % filterstring,locals())
self.db_info_string.set('Number of events: ' +str(len(self.eventsdb_subset)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM