Sunday, 15 July 2018

The Tkinter Button Widget

The Button widget is a standard Tkinter widget, which is used for various kinds of buttons. A button is a widget which is designed for the user to interact with, i.e. if the button is pressed by mouse click some action might be started. They can also contain text and images like labels. While labels can display text in various fonts, a button can only display text in a single font. The text of a button can span more than one line.
The button can only display text in a single font, but the text may span more than one line. In addition, one of the characters can be underlined, for example to mark a keyboard shortcut. By default, the Tab key can be used to move to a button widget.

When to use the Button Widget

Simply put, button widgets are used to let the user say “do this now!,” where this is either given by the text on the button, or implied by the icon displayed in the button. Buttons are typically used in toolbars, in application windows, and to accept or dismiss data entered into a dialog box.

Installation:

$ sudo pip install python-tk
for python 3
$ sudo pip install python3-tk
In Python Script:
import Tkinter
import tkMessageBox
top = Tkinter.Tk()
def helloCallBack():
   tkMessageBox.showinfo( "Hello Python", "Hello World")
B = Tkinter.Button(top, text ="Hello", command = helloCallBack)
B.pack()
top.mainloop()
When the above code is executed, it produces the following result −
TK Button
The following script defines two buttons: one to quit the application and another one for the action, i.e. printing the text “Tkinter is easy to use!” on the terminal.
from tkinter import *
class App:
  def __init__(self, master):
    frame = Frame(master)
    frame.pack()
    self.button = Button(frame, 
                         text="QUIT", fg="red",
                         command=quit)
    self.button.pack(side=LEFT)
    self.slogan = Button(frame,
                         text="Hello",
                         command=self.write_slogan)
    self.slogan.pack(side=LEFT)
  def write_slogan(self):
    print("Tkinter is easy to use!")

root = Tk()
app = App(root)
root.mainloop()
The result of the previous example looks like this:
Example Button class
The following script shows an example, where a label is dynamically incremented by 1 until a stop button is pressed:
import Tkinter as tk

counter = 0 
def counter_label(label):
  counter = 0
  def count():
    global counter
    counter += 1
    label.config(text=str(counter))
    label.after(1000, count)
  count()
 
 
root = tk.Tk()
root.title("Countingnds")
label = tk.Label(root, fg="dark green")
label.pack()
counter_label(label)
button = tk.Button(root, text='Stop', width=25, command=root.destroy)
button.pack()
root.mainloop()
The result of the previous example looks like this:
dynamic label

No comments:

Post a Comment