In this TKinter Tutorial we are going to learn about creating TKinter SpinBox, we can use SpinBox() class for creating of spinbox in tkinter, so a spin box or spin button is a form field enabling users to increase or decrease the number value in the text field by a specific increment (often by 1, 5 or 10).
This is the complete code for this lesson.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
import tkinter as tk from tkinter import scrolledtext class Window(tk.Tk): def __init__(self): super(Window, self).__init__() self.title("Create SpinBox in TKinter") self.minsize(500,400) self.wm_iconbitmap("myicon.ico") self.spin_box() def spin_callback(self): value = self.spin.get() self.controlText.insert(tk.INSERT, value) def spin_box(self): self.spin = tk.Spinbox(self, from_ = 0, to = 10, command = self.spin_callback) self.spin.grid(column = 0, row = 0) scroll_w = 30 scroll_h = 10 self.controlText = scrolledtext.ScrolledText(self, width = scroll_w, height = scroll_h, wrap = tk.WORD) self.controlText.grid(column = 1, row = 2) window = Window() window.mainloop() |
In here we have created our SpinBox, and you can add the spinbox value, for example we have added from 0 up to 10, also we have added a command to the spinbox, we have connected that with spin_callback() method.
1 |
self.spin = tk.Spinbox(self, from_ = 0, to = 10, command = self.spin_callback) |
Also we are using ScrolledText, you need to add the width and height for the ScrolledText.
1 2 3 4 5 6 |
scroll_w = 30 scroll_h = 10 self.controlText = scrolledtext.ScrolledText(self, width = scroll_w, height = scroll_h, wrap = tk.WORD) self.controlText.grid(column = 1, row = 2) |
And this is our method for the spinbox, we have already connected this method with the command of spinbox. in this method first we are going to get the value from the spinbox and after that we insert the value in the ScrolledText.
1 2 3 |
def spin_callback(self): value = self.spin.get() self.controlText.insert(tk.INSERT, value) |
Run the complete code and this is the result.