I tried creating a widget for loop that would only allow one letter input, but I'm running into an issue where it creates text for every widget. I assume the issue lies with the "len" I used.
from tkinter import *
from pynput.keyboard import Key, Controller
root = Tk()
height = 6
width = 5
delta=0
entries = []
def limitSizeDay(*args):
value = dayValue.get()
if len(value) > 1: dayValue.set(value[:1])
dayValue = StringVar()
dayValue.trace('w', limitSizeDay)
for i in range(height): #Rows
newrow = []
for j in range(width): #Columns
b = Entry(root, text="",width=2,font=('Arial', 40, 'bold'), textvariable=dayValue)
b.grid(row=i, column=j)
newrow.append(b)
entries.append(newrow)
def getword(event):
global b
ass = b.get()
print(ass)
keyboard = Controller()
keyboard.press(Key.tab)
keyboard.release(Key.tab)
root.bind('<Return>', getword)
mainloop()
CodePudding user response:
No. The problem is that you have bound every Entry
box to the same textvariable (dayValue
). When you change that one variable, all of the boxes respond. I can't tell what you are really trying to achieve with this. If you want each box to have its own variable, then you need to create a LIST of StringVars
, probably inside the loop so you get the same size.
CodePudding user response:
As Tim said the cause of your problem is binding the same StringVar
to all of the Entry
widgets. To make this work, you need to create a StringVar
for each Entry
in a loop:
for i in range(height): #Rows
newrow = []
for j in range(width): #Columns
dayValue = StringVar()
dayValue.trace('w', limitSizeDay)
b = Entry(root, text="",width=2,font=('Arial', 40, 'bold'), textvariable=dayValue)
b.var = dayValue # Prevent garbage collection (I think)
b.grid(row=i, column=j)
newrow.append(b)
entries.append(newrow)
Then you need to change limitSizeDay
to access the variable.
def limitSizeDay(var, *args):
value = root.globalgetvar(var)
if len(value) > 1: root.globalsetvar(var, value[:1])
The globalgetvar
and globalsetvar
methods allow you to get and set the variable respectively as the usual getvar
and setvar
don't work in this case.