Tkinter

From Hidden Wiki
Revision as of 08:19, 18 April 2020 by Col (talk | contribs)
Jump to navigation Jump to search
Unix Assembly language Mathematics Web development I2P
GhostBSD Assembly Programming Tutorial Statistics Django for Beginners MuWire
GUI Artificial intelligence Artificial neural network Machine learning Messenger
Tkinter Artificial intelligence Artificial neural network Machine Learning Mastery with Python Session

Tkinter is a Python binding to the Tk GUI toolkit. It is the standard Python interface to the Tk GUI toolkit,[1] and is Python's de facto standard GUI.[2] Tkinter is included with standard Linux, Microsoft Windows and Mac OS X installs of Python.

The name Tkinter comes from Tk interface. Tkinter was written by Fredrik Lundh.[3]

Tkinter is free software released under a Python license.[4]


The source codes of this article were tested with Python 3.7.5 on Ubuntu 9.10.


from tkinter import *

or

import tkinter as tk

Input the above line into your Python 3 source code.


Input the below command in your terminal.

sudo apt install python3-tk


Use VSCodium or any ource-code editor to edit your source codes.


You can execute your program like the below command.

python3 cal.py

Elements arrangement by using "pack" and "grid"

root=Tk()

To show a blank window


root.mainloop()

"(Tk object).mainloop()" -> make a window to get an entry


from tkinter import *
root=Tk()
root.mainloop()

complete source code


pussy = widget_name(new_Tk_object, ... )
pussy.pack() 

make a new widget


root = Tk()

sister_pussy = Label(root, text = "sis pussy")
sister_pussy.pack()

complete source code


Displacement of a widget

1. place

2. pack

3. grid

"grid" is similar to a table.


from tkinter import *
root = Tk()

sister_pussy = Label(root, text = "sis pussy")
sister_pussy.pack()

root.mainloop()

complete source code


1 label, 1 text box, and 2 buttons

A window made by "grid".

from tkinter import *
root = Tk()

title = Label(root,text="Input")
txtbox = Entry(root, width = 15)
btn_1= Button(root, text = "Submit", width=10)
btn_2 = Button(root, text= "Cancel", width=10)

title.grid(row=0, column=0)
txtbox.grid(row=0, column=1)
btn_1.grid(row=1,column=1)
btn_2.grid(row=2, column=1)

root.mainloop()

"Entry" is for inputting texts.


btn_1.grid(row=1,column=1)
btn_2.grid(row=1,column=1) 

If two elements have been placed at the same place, the last one replaces the prior one. In this case, the "button 2" will replace the "button 1".

GUI calculator

GUI calculator source code


''' cal.py
A updated tiny calculator using the Tkinter GUI toolkit
you can type in functions contained in module math
for instance type in  tan(pi/180)  then click  =
tested with Python 3.7.5 on Ubuntu 19.10
'''
from math import *
from functools import partial
import tkinter as tk
class MyApp(tk.Tk):
    def __init__(self):
        # the root will be self
        tk.Tk.__init__(self)
        self.title("Darknet TK Calculator")
        # use width x height + x_offset + y_offset (no spaces!)
        #self.geometry("300x150+150+50")
        # or set x, y position only
        self.geometry("+150+50")
        self.memory = 0
        self.create_widgets()
    def create_widgets(self):
        # this also shows the calculator's button layout
        btn_list = [
        '7',  '8',  '9',  '*',  'C',
        '4',  '5',  '6',  '/',  'M->',
        '1',  '2',  '3',  '-',  '->M',
        '0',  '.',  '=',  '+',  'neg' ]
        rel = 'ridge'
        # create all buttons with a loop
        r = 1
        c = 0
        for b in btn_list:
            # partial takes care of function and argument
            cmd = partial(self.calculate, b)
            tk.Button(self, text=b, width=5, relief=rel,
                command=cmd).grid(row=r, column=c)
            c += 1
            if c > 4:
                c = 0
                r += 1
        # use an Entry widget for an editable display
        self.entry = tk.Entry(self, width=33, bg="yellow")
        self.entry.grid(row=0, column=0, columnspan=5)
    def calculate(self, key):
        if key == '=':
            # guard against the bad guys abusing eval()
            if '_' in self.entry.get():
                self.entry.insert(tk.END, " not accepted!")
            # here comes the calculation part
            try:
                result = eval(self.entry.get())
                self.entry.insert(tk.END, " = " + str(result))
            except:
                self.entry.insert(tk.END, "--> Error!")
        elif key == 'C':
            self.entry.delete(0, tk.END)  # clear entry
        elif key == '->M':
            self.memory = self.entry.get()
            # extract the result
            if '=' in self.memory:
                ix = self.memory.find('=')
                self.memory = self.memory[ix+2:]
            self.title('M=' + self.memory)
        elif key == 'M->':
            if self.memory:
               self.entry.insert(tk.END, self.memory)
        elif key == 'neg':
            if '=' in self.entry.get():
                self.entry.delete(0, tk.END)
            try:
                if self.entry.get()[0] == '-':
                    self.entry.delete(0)
                else:
                    self.entry.insert(0, '-')
            except IndexError:
                pass
        else:
            # previous calculation has been done, clear entry
            if '=' in self.entry.get():
                self.entry.delete(0, tk.END)
            self.entry.insert(tk.END, key)
app = MyApp()
app.mainloop()


If you use Ubuntu 19.10 and the file name is "cal.py" and your Python version is 3.7.5, input the below commands in your terminal.

sudo apt install python3-tk
python3 cal.py 


Explanation of the source code

The below link is the origin of the source code.


  • Updated Tiny Tkinter Calculator (Python)

Nov 13th, 2013 9:14 pm

https://www.daniweb.com/programming/software-development/code/467452/updated-tiny-tkinter-calculator-python


The lines confined by three ' are comments. See Python article to see more detailed explanation.


The below codes are for Python 2 so I removed or modified them. Because most people use Python 3 instead of Python 2 in these days.

# avoid integer division by Python2
from __future__ import division

and

try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk


  • Python Language - Integer Division | python Tutorial

https://riptutorial.com/python/example/2797/integer-division


  • Difference between tkinter and Tkinter

2013-07-24

https://stackoverflow.com/questions/17843596/difference-between-tkinter-and-tkinter


from math import *
from functools import partial
import tkinter as tk

The second line means that importing "partial" from "functools". The first line means that importing everything from "math". The last line means that importing "tkinter" as the name "tk".


Under MyApp class, there are three functions defined by "def". Definition is different to declaration.

Description

As with most other modern Tk bindings, Tkinter is implemented as a Python wrapper around a complete Tcl interpreter embedded in the Python interpreter. Tkinter calls are translated into Tcl commands which are fed to this embedded interpreter, thus making it possible to mix Python and Tcl in a single application.

There are several popular GUI library alternatives available, such as wxPython, PyQt (PySide), Pygame, Pyglet, and PyGTK.

Some definitions

Window

This term has different meanings in different contexts, but in general it refers to a rectangular area somewhere on the user's display screen.

Top Level Window

A window that exists independently on the screen. It will be decorated with the standard frame and controls for the desktop manager. It can be moved around the desktop, and can usually be resized.

Widget

The generic term for any of the building blocks that make up an application in a graphical user interface.

  • Core widgets: The containers: frame, toplevel, paned window. The buttons: button, radiobutton, checkbutton (checkbox), menubutton (combobox). The text widgets: label, labelframe, message, text. The entry widgets: scale, scroll, listbox, slider, spinbox, entry (singleline), text (multiline), and canvas (vector and pixel graphics).
  • There are the extension widgets: tk_optionMenu, tk_dialog, tk_messageBox, tk_getOpenFile, tk_getSaveFile, tk_chooseColor, tk_chooseDirectory.
  • Python 2.7 and Python 3.1 incorporate the "themed Tk" ("ttk") functionality of Tk 8.5.[5][6] This allows Tk widgets to be easily themed to look like the native desktop environment in which the application is running, thereby addressing a long-standing criticism of Tk (and hence of Tkinter).

Frame

In Tkinter, the Frame widget is the basic unit of organization for complex layouts. A frame is a rectangular area that can contain other widgets.

Child and parent

When any widget is created, a parent-child relationship is created. For example, if you place a text label inside a frame, the frame is the parent of the label.

A minimal application

Here is a minimal Python 3 Tkinter application with one widget:[7] (For Python 2, the only difference is the word "tkinter" in the import command will be capitalized to "Tkinter.") <source lang="python" line="1">

  1. !/usr/bin/env python3

from tkinter import * root = Tk() # Create the root (base) window w = Label(root, text="Hello, world!") # Create a label with words w.pack() # Put the label into the window root.mainloop() # Start the event loop </source>[8]

Process

There are four stages to creating a widget

Create
create it within a frame
Configure
change the widgets attributes
Pack
pack it into position so it becomes visible
Bind
bind it to a function or event. [9]

These are often compressed and the order can vary.

Simple application

Using the object orientated paradigm in Python, a simple program would be (requires Tcl version 8.6, which is not used by Python on MacOS by default): <source lang="python" line="1">

  1. !/usr/bin/env python3

import tkinter as tk

class Application(tk.Frame):

   def __init__(self, master=None):
       tk.Frame.__init__(self, master)
       self.grid()  
       self.createWidgets()
   def createWidgets(self):
       self.mondialLabel = tk.Label(self, text='Hello World')
       self.mondialLabel.config(bg="#00ffff")
       self.mondialLabel.grid()
       self.quitButton = tk.Button(self, text='Quit', command=self.quit)
       self.quitButton.grid()

app = Application() app.master.title('Sample application') app.mainloop() </source>

  • line 1: Hashbang directive to the program launcher, allowing the selection of an appropriate interpreter executable, when self-executing.[10]
  • line 2: This line imports the tkinter module into your program's namespace, but renames it as tk.
  • line 4: The application class inherits from Tkinter's Frame class.
  • line 6: Defines the function that sets up the Frame
  • line 7: Calls the constructor for the parent class, Frame.
  • line 11: Defining the widgets
  • line 12: Creates a label, named MondialLabel with the text "Hello World"
  • line 13: Sets the MondialLabel background colour to cyan
  • line 14: Places the label on the application so it is visible using the grid geometry manager method
  • line 15: Creates a button labeled “Quit”.
  • line 16: Places the button on the application. Grid, place and pack are all methods of making the widget visible
  • line 18: The main program starts here by instantiating the Application class.
  • line 19: This method call sets the title of the window to “Sample application”.
  • line 20: Starts the application's main loop, waiting for mouse and keyboard events.

See also

References

External links

Template:Widget toolkits