Um mein Problem vereinfacht zu veranschaulichen, folgender Code:
Code: Alles auswählen
import tkinter as tk # python 3.x
# import Tkinter as tk # python 2.x
class Example(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.scaling_factor = tk.DoubleVar()
self.entry = tk.Entry(self, textvariable=self.scaling_factor)
self.entry.pack(side="top", fill="x")
self.scaling_factor.trace('w', self._instant_scaling)
def _instant_scaling(self, *args):
scaled_length = 2 * self.scaling_factor.get()
print(scaled_length)
if __name__ == "__main__":
root = tk.Tk()
Example(root).pack(fill="both", expand=True)
root.mainloop()
Code: Alles auswählen
Traceback (most recent call last):
File "C:\Users\Seb\Miniconda3\envs\py_34\lib\tkinter\__init__.py", line 1538, in __call__
return self.func(*args)
File "entryval.py", line 19, in _get_value
self.scaling_factor.get()
File "C:\Users\Seb\Miniconda3\envs\py_34\lib\tkinter\__init__.py", line 377, in get
return getdouble(self._tk.globalgetvar(self._name))
ValueError: could not convert string to float:
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "entryval.py", line 27, in <module>
root.mainloop()
File "C:\Users\Seb\Miniconda3\envs\py_34\lib\tkinter\__init__.py", line 1125, in mainloop
self.tk.mainloop(n)
File "C:\Users\Seb\Miniconda3\envs\py_34\lib\tkinter\__init__.py", line 1542, in __call__
self.widget._report_exception()
AttributeError: 'DoubleVar' object has no attribute '_report_exception'
Füge also try...except hinzu:
Code: Alles auswählen
import tkinter as tk # python 3.x
# import Tkinter as tk # python 2.x
class Example(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.scaling_factor = tk.DoubleVar()
self.entry = tk.Entry(self, textvariable=self.scaling_factor)
self.entry.pack(side="top", fill="x")
self.scaling_factor.trace('w', self._instant_scaling)
def _instant_scaling(self, *args):
try:
scaled_length = 2 * self.scaling_factor.get()
print(scaled_length)
except ValueError:
pass
if __name__ == "__main__":
root = tk.Tk()
Example(root).pack(fill="both", expand=True)
root.mainloop()
Ist dies so schlechter Stil und es gibt dafür eine "saubere" Alternative?
(über die Validierung der Eingabe ist es mir nicht gelungen...mithilfe von: https://stackoverflow.com/a/4140988)
Gruß Seb