【问题标题】:Python/Tkinter autofocus when entry is filled填充条目时的 Python/Tkinter 自动对焦
【发布时间】:2020-07-21 08:11:08
【问题描述】:

我正在尝试使用一个比较两个字符串的简单 GUI 运行一个简单的脚本。如您所见,我添加了两个输入字段和一个运行我的检查功能的检查按钮。一开始 .focus() 位于第一个条目小部件上,然后我需要输入一个值选择第二个条目小部件输入一个值,然后按检查脚本以比较两个给定值。

import tkinter as tk
from tkinter import ttk



win = tk.Tk()
win.title("Vitek magacin")
win.geometry("200x150")
win.configure(background='gold')

def check():
    c1=no1.get()
    c2=no2.get()

    if c1 == c2:
        print("You win a silly price")
    else:
        print("You win nothing old men")


no1=tk.StringVar()
no2=tk.StringVar()

inputa = ttk.Entry(win, width=12, textvariable=no1)
inputa.grid(column=0, row=1)
inputa.focus()

inputb = ttk.Entry(win, width=12, textvariable=no2)
inputb.grid(column=0, row=2)

ButtonCheck = ttk.Button(win, text='Check', 
command=check)
ButtonCheck.grid(column=0, row=3)

win.mainloop()

所以我想做的是: 当我填写条目一以将焦点切换到条目二并且填充条目二时,我希望它运行检查功能,删除条目字段并重新开始,因为这些输入将来自条形码阅读器,我希望它尽可能自动化。有人可以帮忙吗?

【问题讨论】:

  • 只需在check()末尾添加no1.set('')no2.set('')inputa.focus()即可。
  • 我不明白你不能编辑或写一个例子吗?如果它这么简单,你就是一个天才! :D
  • 如何使用条形码阅读器填写条目?是否有任务不断检查条形码阅读器是否有数据?
  • 他们的计算机接受条形码阅读器作为输入设备,就像键盘或鼠标一样,上面有一个按钮,当你想阅读条形码时按下它......它会发射激光并你得到一个输入。
  • 那么,如果条码的长度不同,怎么知道条码被读取完整呢?

标签: python tkinter input widget compare


【解决方案1】:

我会用 bind 方法解决这个问题。 这有点错误并且有一些缺点,但是如果您不按任何其他键,它就可以工作。例如,如果你按 'fn' 12 次,就会出现问题,但我认为你可以解决它。 思路是程序计算击键次数并与输入字段的宽度进行比较,如果输入字段完全填满,则程序关注第二个输入字段,如果第二个输入字段也完全填满,则程序执行功能。

from tkinter import *
root = Tk()
root.title("Vitek magacin")
root.geometry("200x150")
root.configure(background='gold')
s = 0
def check():
    c1=inputa.get()
    c2=inputb.get()
    if c1 == c2:
        print("You win a silly price")
    else:
        print("You win nothing old men")
def checker(event):
    global s
    s += 1
    if s==inputa['width']:
        inputb.focus()
    if s==inputa['width']+inputb['width']:
        check()
inputa = Entry(root, width=12)
inputa.grid(column=0, row=1)
inputa.focus()
inputb = Entry(root, width=12)
inputb.grid(column=0, row=2)
ButtonCheck = Button(root, text='Check', command=check)
ButtonCheck.grid(column=0, row=3)
root.bind('<Key>', checker)
root.mainloop()

【讨论】:

  • 我也想过这个,但这是否意味着它只会在我只填充 12 个字符时才会跳转焦点?当我尝试使用 6 个字符扫描信息时它不起作用?
  • 是的,只有填充12个字符才会跳转焦点,但你可以这样解决:root.bind('&lt;Enter&gt;', function)这意味着如果你写的东西少于12个字符并按下回车键它会跳转关注下一个条目或执行“检查”功能
  • 我没有输入按钮,只有条形码阅读器,也许还有触摸屏,但这很有帮助,我很可能会使用它。非常感谢朋友。
猜你喜欢
  • 2017-08-12
  • 1970-01-01
  • 1970-01-01
  • 2010-12-28
  • 1970-01-01
  • 2011-05-22
  • 1970-01-01
  • 2022-08-14
  • 2012-04-02
相关资源
最近更新 更多