tkinter 11 spinbox

Reference

简介

Spinbox 组件(Tk8.4 新增)是 Entry 组件的变体,与Entry类似,但可以指定输入范围,从一些固定的值中选取一个。使用:Spinbox 组件通常用于在限定数字中选取的情况下代替普通的Entry组件

属性和方法

几乎和Entry方法一样,不同在于,Spinbox 组件可以通过范围(from, to,increment)或者元组(value)指定允许用户输入的内容。

属性

方法

实例

    def _gui_int(self):
        frm1 = tk.Frame(self.window)
        frm1.pack(anchor='w')
        frm2 = tk.Frame(self.window)
        frm2.pack(anchor='w')
        frm3 = tk.Frame(self.window)
        frm3.pack(anchor='w')
        # 1. spinbox 的基本用法
        def call_back():  # 当上下的按钮被触发的时候调用
            print(spb.get())
        spb = tk.Spinbox(frm1, bg='red', fg='white',
                         from_=20, to=30, increment=2, command=call_back)
        spb.pack(side=tk.RIGHT)
        spb['text'] = '25'
        tk.Label(frm1, text="Age:", justify='right',
                 anchor='e', width=10, bg='grey').pack(side=tk.LEFT)

        values_in = ('perl', 'python', 'ruby', 'lua')

        # 2. spin输入验证
        def validate_input(contents):
            # print(contents)
            return contents in values_in
        validate_cmd = self.window.register(validate_input)

        def invalidate_input():
            # method 1
            spb2.delete(0, tk.END)
            print(spb2['validate'])

            # method 2
            # var.set('python')
            # print(spb2['validate'])
            # spb2['validate']='focusout'

        var = tk.StringVar()
        spb2 = tk.Spinbox(frm2, bg='red', fg='white',
                          value=values_in,
                          textvariable=var,
                          validate='focusout',
                          validatecommand=(validate_cmd, '%P'),
                          invalidcommand=invalidate_input)
        spb2.pack(side=tk.RIGHT)
        var.set("python")
        tk.Label(frm2, text="Party:", justify='right', anchor='e', width=10, bg='grey').pack(side=tk.LEFT)
        def show_info():
            info = "age: " + spb.get()
            info += '\nSupport:' + var.get()
            t1.delete(0.0, tk.END)
            t1.insert(0.0, info)

        tk.Button(frm3, bg='green', text='show info', command=show_info).pack(anchor='nw')
        t1 = tk.Text(frm3, width=100, height=3, bg='black', fg='red')
        t1.pack(anchor='nw')
Table of Contents