我有一个输入字段并弹出键盘窗口。每当用户单击输入字段时,它都会通过键盘接受输入。输入用户输入时读取当前光标位置时遇到的问题之一总是显示光标位置为“零”,并且在通过键盘输入输入时用户在输入字段中看不到任何光标。
代码:
from tkinter import *
from tkinter import simpledialog
class Gui(Toplevel):
def __init__(self, parent,*args):
Toplevel.__init__(self, parent)
self.title('User input window')
self.geometry('450x350')
self.EntryVar=StringVar()
self.label = Label(self, text='User Input:', width=15, background='white', justify=CENTER,
font='-weight bold')
self.entry = Entry(self, width=15, background='white', textvariable=self.EntryVar,
font='-weight bold')
self.label.grid(row=2,padx=10, pady=5, column=0, sticky='E')
self.entry.grid(row=2,padx=10, pady=5, column=1, sticky='E')
self.entry.bind('<FocusIn>', self.keypad_popup)
def keypad_popup(self,event):
new = numPad(self, event.widget)
class numPad(simpledialog.Dialog):
def __init__(self, parent, *args):
self.focus = args[0]
self.parent = parent
self.top = Toplevel(parent)
self.top.title('Keypad')
self.top.grab_set()
self.createWidgets()
def createWidgets(self):
btn_list = ['6', '1', '2', '3', '0','C', 'D']
r = 1
c = 0
n = 0
btn = []
for label in btn_list:
cmd = lambda x=label: self.click(x)
button = Button(self.top, text=label, width=10, height=5, command=cmd)
btn.append(button)
btn[-1].grid(row=r, column=c)
n += 1
c += 1
if c == 3:
c = 0
r += 1
def click(self, label):
if label == 'D' and self.focus == self.parent.entry:
currentText = self.parent.EntryVar.get()
self.parent.EntryVar.set(currentText[:-1])
elif label == 'C':
self.top.destroy()
self.top.master.focus()
elif self.focus == self.parent.entry:
currentText = self.parent.entry.get()
self.parent.EntryVar.set(currentText + label)
print('Cursor position:', self.parent.entry.index(INSERT))
if __name__ == '__main__':
root = Tk()
root.title('root window')
root.geometry("150x150")
app = Gui(root)
root.mainloop()
答案 0 :(得分:0)
通过关联变量设置值不会更改光标位置,除非先前的位置超出了新值的末尾。由于光标位置从0开始并且您没有更改,所以它总是为零。
如果要确保在更改值后插入光标位于末尾,可以使用icursor
方法。
示例:
self.parent.entry.icursor("end")