2

我想知道如何设置 TTK 输入字段中允许的最大字符数。我还想将条目限制为仅输入整数,似乎在网上找不到太多。无论如何,这是我的代码:

from tkinter import *
from tkinter import ttk


root = Tk()
root.title("Alarm Interface")
mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)

code = IntVar()


code_entry= ttk.Entry(mainframe, width=7, textvariable=code)
code_entry.grid(columnspan = 2, column=2, row=5, sticky=(W, E))

ttk.Button(mainframe, text="1").grid(column=1, row=1, sticky=NW)
ttk.Button(mainframe, text="2").grid(column=2, row=1, sticky=NW)
ttk.Button(mainframe, text="3").grid(column=3, row=1, sticky=NW)
ttk.Button(mainframe, text="4").grid(column=1, row=2, sticky=NW)
ttk.Button(mainframe, text="5").grid(column=2, row=2, sticky=NW)
ttk.Button(mainframe, text="6").grid(column=3, row=2, sticky=NW)
ttk.Button(mainframe, text="7").grid(column=1, row=3, sticky=NW)
ttk.Button(mainframe, text="8").grid(column=2, row=3, sticky=NW)
ttk.Button(mainframe, text="9").grid(column=3, row=3, sticky=NW)
ttk.Button(mainframe, text="Clear").grid(column=1, row=4, sticky=NW)
ttk.Button(mainframe, text="0").grid(column=2, row=4, sticky=NW)
ttk.Button(mainframe, text="Delete").grid(column=3, row=4, sticky=NW)

ttk.Label(mainframe, text="Enter Code:").grid(column=1, row=5, sticky=W)




for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5)

root.mainloop()

谢谢,想法是这是警报系统的简单界面,数字范围为0-9。

4

1 回答 1

1

您想使用条目小部件的validatecommandvalidate属性。这个答案中描述了如何做到这一点:https ://stackoverflow.com/a/4140988/7432

这是一个简单的示例,它显示了如何禁止任何不会导致 0 到 999 之间的数字的输入(但允许空字符串):

import Tkinter as tk
import ttk

class ConstrainedEntry(ttk.Entry):
    def __init__(self, *args, **kwargs):
        ttk.Entry.__init__(self, *args, **kwargs)

        vcmd = (self.register(self.on_validate),"%P")
        self.configure(validate="key", validatecommand=vcmd)

    def disallow(self):
        self.bell()

    def on_validate(self, new_value):
        try:
            if new_value.strip() == "": return True
            value = int(new_value)
            if value < 0 or value > 999:
                self.disallow()
                return False
        except ValueError:
            self.disallow()
            return False

        return True

class Example(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)
        l = ttk.Label(self, text="Enter a number between 0 and 999:", anchor="w")
        e = ConstrainedEntry(self, width=4)
        l.pack(side="top")
        e.pack(side="top")

root = tk.Tk()
Example(root).pack(side="top", fill="both", expand=True)
root.mainloop()
于 2013-03-22T18:58:05.290 回答