Reputation: 461
I have function which adds number to tk.StringVar()
. I'm creating numeric buttons for my Gui in loop. It worked perfect until I tried to add binds to keyboard. Now clicking on keyboard e.g. 7 will behave as expected. StringVar()
will be appended by 7, but when I try to use my mouse to click Gui button it adds 1. Instead 7 I will get 17 now. Removing those two self.bind
s brings back proper way of working for Gui buttons. Here is my code:
import tkinter as tk
import tkinter.ttk as ttk
class Gui(tk.Tk):
def __init__(self):
super().__init__()
self.user_input = tk.StringVar()
tk.Label(self, textvariable=self.user_input, font=("Times New Roman",30)).grid(row=0, column =0)
for button in self.create_buttons(self): button.grid()
def write(self, *_, button=None):
current = self.user_input.get()
if button:
current += button
else:
current = current[:-1]
self.user_input.set(current)
def create_buttons(self, frame):
buttons = []
for x in range(10):
func = lambda *_, x=x: self.write(button=str(x))
buttons.append(ttk.Button(frame, text=str(x), command=func))
self.bind('<'+str(x)+'>', func)
self.bind('<KP_'+str(x)+'>', func)
buttons.append(ttk.Button(frame, text="<-", command=self.write))
self.bind("<BackSpace>", self.write)
return buttons
Gui().mainloop()
What am I missing here? Why self.bind
modifies my program that way and why it adds exactly 1, not any other number? How can I correct it?
Upvotes: 1
Views: 60
Reputation: 8308
So the only change you need to do in your code is in the create_button()
function and its:
def create_buttons(self, frame):
buttons = []
for x in range(10):
func = lambda *_, x=x: self.write(button=str(x))
buttons.append(ttk.Button(frame, text=str(x), command=func))
self.bind(str(x), func)
self.bind('<KP_'+str(x)+'>', func)
buttons.append(ttk.Button(frame, text="<-", command=self.write))
self.bind("<BackSpace>", self.write)
return buttons
this will stop the weird behavior of adding 1 to the desired key. to bind the key stroke of numeric value or even simple char you need only the string representation of that value for more sophisticated presses you can see the bind()
table in the following link. You don't need to add the "<",">" to bind the desired numeric key.
If you still want to keep the notion with the "<",">" you can do it with the following line instead of the one mentioned above without "<",">":
self.bind('<KeyPress-'+str(x)+'>', func)
you can see the full dodumantion on proper bindings etc here
Upvotes: 2