gpt4 book ai didi

python - Tkinter - 输入框 - 日期格式

转载 作者:太空宇宙 更新时间:2023-11-03 12:34:03 25 4
gpt4 key购买 nike

我想要一个用于输入日期的输入框,以便用户只能以一种方式输入。

键入前的输入框如下所示(没有下划线)__/__/____,以及 / 不会在用户键入日期时被删除。

谢谢

最佳答案

感谢@Bryan Oakley 的重要提示,我想出了这个工作代码。

(更新:投入了几年的编程经验和一些近期读者对改进代码的敏锐眼光。)

from __future__ import print_function

try:
import Tkinter as tk
except ImportError:
import tkinter as tk


class DateEntry(tk.Frame):
def __init__(self, master, frame_look={}, **look):
args = dict(relief=tk.SUNKEN, border=1)
args.update(frame_look)
tk.Frame.__init__(self, master, **args)

args = {'relief': tk.FLAT}
args.update(look)

self.entry_1 = tk.Entry(self, width=2, **args)
self.label_1 = tk.Label(self, text='/', **args)
self.entry_2 = tk.Entry(self, width=2, **args)
self.label_2 = tk.Label(self, text='/', **args)
self.entry_3 = tk.Entry(self, width=4, **args)

self.entry_1.pack(side=tk.LEFT)
self.label_1.pack(side=tk.LEFT)
self.entry_2.pack(side=tk.LEFT)
self.label_2.pack(side=tk.LEFT)
self.entry_3.pack(side=tk.LEFT)

self.entries = [self.entry_1, self.entry_2, self.entry_3]

self.entry_1.bind('<KeyRelease>', lambda e: self._check(0, 2))
self.entry_2.bind('<KeyRelease>', lambda e: self._check(1, 2))
self.entry_3.bind('<KeyRelease>', lambda e: self._check(2, 4))

def _backspace(self, entry):
cont = entry.get()
entry.delete(0, tk.END)
entry.insert(0, cont[:-1])

def _check(self, index, size):
entry = self.entries[index]
next_index = index + 1
next_entry = self.entries[next_index] if next_index < len(self.entries) else None
data = entry.get()

if len(data) > size or not data.isdigit():
self._backspace(entry)
if len(data) >= size and next_entry:
next_entry.focus()

def get(self):
return [e.get() for e in self.entries]


if __name__ == '__main__':
win = tk.Tk()
win.title('DateEntry demo')

dentry = DateEntry(win, font=('Helvetica', 40, tk.NORMAL), border=0)
dentry.pack()

win.bind('<Return>', lambda e: print(dentry.get()))
win.mainloop()

关于python - Tkinter - 输入框 - 日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13242970/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com