jiahuiding jiahuiding - 18 days ago 7
Python Question

fixing the function StringVar_WithHistory

from tkinter import StringVar
class StringVar_WithHistory(StringVar):
def __init__(self):
self.history = []

def set (self,value):
if StringVar.get(self) != value:
StringVar.set(self, value)
self.history.append(value)

def undo (self):
StringVar.set(self,history[-1])
self.history.pop()

from tkinter import OptionMenu
class OptionMenuUndo(OptionMenu):
def __init__(self,parent,title,*option_tuple,**configs):
self.result = StringVar_WithHistory()
self.result.set(title)
OptionMenu.__init__(self,parent,self.result,*option_tuple,**configs)


def get(self):
return self.result.get()


def undo(self):
self.result.undo()


def simulate_selection(self,option):
self.result.set(option)


I am working on the StringVar_WithHistory class to make it apply to the OptionMenuUndo class. The StringVar_WithHistory has three methods.

init (self): initializes the base class; creates a history list for storing the values set is called with.

set (self,value): if the value is different from the current value, set the StringVar to value and remember it in the history list (if it is the same as the current value, do nothing: no new selection).

undo (self): undo the most recently selected option by updating the StringVar and the history list

I tried to run the code and I got the following error:

Traceback (most recent call last):
omu = OptionMenuUndo(main, 'Choose Option', 'option1','option2','option3')
self.result.set(title)
if StringVar.get(self) != value:
value = self._tk.globalgetvar(self._name)
AttributeError: 'NoneType' object has no attribute 'globalgetvar'


can someone tell me how to fix myStringVar_WithHistory? thanks

Answer

You forgot StringVar.__init__()

BTW: you have to use [-2] or first pop value.

PS. you have to check self.history size before you get element because it can be empty.

from tkinter import StringVar

class StringVar_WithHistory(StringVar):

    def __init__(self, **kwargs):
        StringVar.__init__(self, **kwargs)
        self.history = []

    def set(self, value):
        if StringVar.get(self) != value:
            StringVar.set(self, value)
            self.history.append(value)
        #print('DEBUG:', self.history)

    def undo(self):
        StringVar.set(self, self.history[-2])
        self.history.pop()
        #print('DEBUG:', self.history)

import tkinter as tk

root = tk.Tk()

a = StringVar_WithHistory(value='TEST')
print(a.get())
a.set('Hello')
print(a.get())
a.set('World')
print(a.get())
a.undo()
print(a.get())
a.undo() # error because self.history is empty

root.mainloop()
Comments