每当按下向上或向下箭头键时,我都试图使输入值增加或减少。要做到这一点,我需要首先找到关注的条目,并且我试图这样做" .focus_get()"。问题是我无法弄清楚它的工作原理或返回方式。它为每个条目返回1个唯一编号,例如:" .45191744"但是每次运行程序时这个数字都会改变。 运行代码时,以下数字表示最近5次尝试。 " 0.50518728" " 0.53009096" " 0.55889592" " 0.51891896"
如何获得焦点条目的变量名称?
这是我的代码:
def get_focus1(event):
print("return: event.widget is", event.widget)
print("focus is:", window2.focus_get())
print(window2.focus_get())
print(help(window2.Entry))
window2 = Tk()
eyear1 = Entry(window2, width=4, font=("Helvetica", 16)) # Entry for year
eyear1.insert(10, defaultYear)
eyear1.grid(row=1, column=1)
emonth1 = Entry(window2, width=4, font=("Helvetica", 16)) # Entry for Month
emonth1.insert(10, defaultMonth)
emonth1.grid(row=1, column=2)
eday1 = Entry(window2, width=4, font=("Helvetica", 16)) # Entry for day
eday1.insert(10, defaultDay)
eday1.grid(row=1, column=3)
window2.bind('<Left>', get_focus1)
mainloop()
答案 0 :(得分:4)
focus_get
返回实际对象。你想做什么,假设你没有充分使用(参见Bryan的评论),是清除文本并重新写入新值(显然要做一些验证) 。你最终得到的是这样的:textvariable
from tkinter import *
def up(event):
# warning, exceptions can happen
old = int(event.widget.get()) # this gives back the actual object!
event.widget.delete(0, END) # delete existing text
event.widget.insert(10, old + 1) # put new text in
def down(event):
# warning, exceptions can happen
old = int(event.widget.get()) # this gives back the actual object!
event.widget.delete(0, END) # delete existing text
event.widget.insert(10, old - 1) # put new text in
window2 = Tk()
eyear1 = Entry(window2, width=4, font=("Helvetica", 16)) # Entry for year
eyear1.insert(10, 2015)
eyear1.grid(row=1, column=1)
emonth1 = Entry(window2, width=4, font=("Helvetica", 16)) # Entry for Month
emonth1.insert(10, 1)
emonth1.grid(row=1, column=2)
eday1 = Entry(window2, width=4, font=("Helvetica", 16)) # Entry for day
eday1.insert(10, 10)
eday1.grid(row=1, column=3)
# bind both keys to corresponding event handlers
window2.bind('<Up>', up)
window2.bind('<Down>', down)
mainloop()
答案 1 :(得分:1)
请记住,当您调用print时,您将获得对象的表示,而不一定是对象本身。要向您展示正在进行的操作,请将其添加到get_focus1
功能:
print("focus object class:", window2.focus_get().__class__)
您应该看到它确实返回了对Entry
小部件的引用,这意味着您可以调用该对象上的所有常规方法。