Tkinter

From Hidden Wiki
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, Windows and macOS 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.8.2 on Ubuntu 20.04.


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 source-code editor to edit your source codes.


You can execute your program like the below command.

python3 cal.py

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.")


#!/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 


cite web |last1=Fleck |first1=Dan |title=Tkinter – GUIs in Python |url=https://cs.gmu.edu/~dfleck/classes/cs112/spring08/slides/tkinter.pdf |website=CS112 |publisher=George Mason University |accessdate=18 August 2018

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. [8]

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):


#!/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()


  • line 1: Hashbang directive to the program launcher, allowing the selection of an appropriate interpreter executable, when self-executing.[9]
  • 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.


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

http://uoxqi4lrfqztugili7zzgygibs4xstehf5hohtkpyqcoyryweypzkwid.onion/?img=361615491111.png

http://hostxvivwx3lzvfdnof2muv7q5fkcovkfa3nexlnl5zrelif2mawxkad.onion/image.php?di=631T


http://pdogfxf7k6lyqe7uhmrokpc74nk2td75m4al5t6uvfhdvvxvng3nazid.onion\/tnibabrS30.jpg

http://3b6clio4syptsnvvtzyxifqvtizyazgyowpp3v5f7dj3mzmfhyoy4iyd.onion/images/8f98719adf96e79c9647c790631c1c2e.png


Source code

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()

General explanation for 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.

Make a blank window

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
app = MyApp()
app.mainloop()

Fill the window with widgets

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):
        print("Hello?")
app = MyApp()
app.mainloop()


return

Why would you use the return statement in Python?


The print() function writes, i.e., "prints", a string or a number on the console. The return statement does not print out the value it returns when the function is called. It however causes the function to exit or terminate immediately, even if it is not the last statement of the function.

Functions that return values are sometimes called fruitful functions. In many other languages, a function that doesn’t return a value is called a procedure.

In the given code the value returned (that is 2) when function foo() is called is used in the function bar(). These return values are printed on console only when the print statements are used as shown below.


Example

def foo():
    print("Hello from within foo")
    return 2
def bar():
    return 10*foo()
print(foo())
print(bar())


Output

Hello from within foo
2
Hello from within foo
20


We see that when foo() is called from bar(), 2 isn't written to the console. Instead it is used to calculate the value returned from bar().

https://www.tutorialspoint.com/Why-would-you-use-the-return-statement-in-Python


functools.partial

Partial functions You can create partial functions in python by using the partial function from the functools library.

Partial functions allow one to derive a function with x parameters to a function with fewer parameters and fixed values set for the more limited function.

Import required:

from functools import partial


This code will return 21.

from functools import partial

def multiply(x,y):
    return x * y

loli = partial(multiply,3)
print(loli(7))


7*3 = 21


An important note: the default values will start replacing variables from the left. The 2 will replace x. y will equal 4 when dbl(4) is called. It does not make a difference in this example, but it does in the example below.


Exercise

Edit the function provided by calling partial() and replacing the first three variables in func(). Then print with the new partial function using only one input variable so that the output equals 26.

#Following is the exercise, function provided:
from functools import partial
def func(u,v,w,x):
    return u*5 + v*4 + w*3 + x
#Enter your code here to create and print with your partial function
baby = partial(func,1,2,3)
print(baby(4))


1*5 + 2*4 + 3*3 + 4 = 26


functools — Higher-order functions and operations on callable objects


The functools module is for higher-order functions: functions that act on or return other functions. In general, any callable object can be treated as a function for the purposes of this module.


The functools module defines the following functions:


functools.partial(func, /, *args, **keywords)

Return a new partial object which when called will behave like func called with the positional arguments args and keyword arguments keywords. If more arguments are supplied to the call, they are appended to args. If additional keyword arguments are supplied, they extend and override keywords. Roughly equivalent to:

def partial(func, /, *args, **keywords):
    def newfunc(*fargs, **fkeywords):
        newkeywords = {**keywords, **fkeywords}
        return func(*args, *fargs, **newkeywords)
    newfunc.func = func
    newfunc.args = args
    newfunc.keywords = keywords
    return newfunc


The partial() is used for partial function application which “freezes” some portion of a function’s arguments and/or keywords resulting in a new object with a simplified signature. For example, partial() can be used to create a callable that behaves like the int() function where the base argument defaults to two:

>>> from functools import partial
>>> basetwo = partial(int, base=2)
>>> basetwo.__doc__ = 'Convert base 2 string to an int.'
>>> basetwo('10010')
18


https://docs.python.org/3/library/functools.html

How To Convert Data Types in Python 3

Converting Integers to Floats

f = 57
print(float(f))


Output
57.0

Converting Floats to Integers

b = 125.0
c = 390.8

print(int(b))
print(int(c))


Output
125
390

When converting floats to integers with the int() function, Python cuts off the decimal and remaining numbers of a float to create an integer. Even though we may want to round 390.8 up to 391, Python will not do this through the int() function.

Numbers Converted Through Division

In Python 3, relevant quotients are converted from integers to floats when doing division though they are not in Python 2. That is, when you divide 5 by 2, in Python 3 you will get a float for an answer (2.5):

a = 5 / 2
print(a)


Output
2.5

In Python 2, since you were dealing with two integers, you would receive an integer back as your answer, instead: 5 / 2 = 2.

Converting Numbers to Strings

a = str(12)
print(a)


Output
12


user = "Sammy"
lines = 50

print("Congratulations, " + user + "! You just wrote " + lines + " lines of code.")
When we run this code, we receive the following error:


Output
TypeError: Can't convert 'int' object to str implicitly


We’re not able to concatenate strings and integers in Python, so we’ll have to convert the variable "lines" to be a string value:

user = "Sammy"
lines = 50

print("Congratulations, " + user + "! You just wrote " + str(lines) + " lines of code.")

Now, when we run the code, we receive the following output that congratulates our user on their progress:

Output
Congratulations, Sammy! You just wrote 50 lines of code.

Converting Strings to Numbers

lines_yesterday = "50"
lines_today = "108"

lines_more = lines_today - lines_yesterday

print(lines_more)


Output
TypeError: unsupported operand type(s) for -: 'str' and 'str'

Because the two numeric values were stored in strings, we received an error. The operand "-" for subtraction is not a valid operand for two string values.


Let’s modify the code to include the int() method that will convert the strings to integers, and allow us to do math with values these that were originally strings.

lines_yesterday = "50"
lines_today = "108"

lines_more = int(lines_today) - int(lines_yesterday)

print(lines_more)


Output
58

Python input() Function

print('Enter any number:')
num = input()
print('Your number is ' + num + '.')


num = input('Enter any number: ')
print('Your number is ' + num + '.')


if elif else

num = float(input('Enter any number: '))
if num >= -3.47:
    print("Your number is -3.47 or bigger than it.")
else:
    print("Your number is smaller than -3.47.")


num = float(input('Enter any number: '))

if num >= -3.47:
    if num == -3.47:
        print("Your namuber is -3.47.")
    else:
        print("Your number is bigger than -3.47.")
else:
    print("Your number is smaller than -3.47.")


num = float(input('Enter any number: '))

if num > -3.47:
    print("Your number is bigger than -3.47.")
elif num == -3.47:
    print("Your number is -3.47.")
else:
    print("Your number is smaller than -3.47.")

try except

The "try" block lets you test a block of code for errors.

The "except" block lets you handle the error.

The "finally" block lets you execute code, regardless of the result of the try- and except blocks.

Exception Handling

When an error occurs, or exception as we call it, Python will normally stop and generate an error message.

These exceptions can be handled using the "try" statement:


Example

The "try" block will generate an exception, because "x" is not defined:

try:
  print(x)
except:
  print("An exception occurred")


Since the try block raises an error, the except block will be executed.

Without the try block, the program will crash and raise an error:


Example

This statement will raise an error, because "x" is not defined:

print(x)


Many Exceptions

You can define as many exception blocks as you want, e.g. if you want to execute a special block of code for a special kind of error:


Example

Print one message if the try block raises a "NameError" and another for other errors:

try:
  print(x)
except NameError:
  print("Variable x is not defined")
except:
  print("Something else went wrong")

Else

You can use the "else" keyword to define a block of code to be executed if no errors were raised:


Example

In this example, the "try" block does not generate any error:

try:
  print("Hello")
except:
  print("Something went wrong")
else:
  print("Nothing went wrong")


Finally

The "finally" block, if specified, will be executed regardless if the try block raises an error or not.


Example

try:
  print(x)
except:
  print("Something went wrong")
finally:
  print("The 'try except' is finished")


This can be useful to close objects and clean up resources:


Example

Try to open and write to a file that is not writable:

try:
  f = open("demofile.txt")
  f.write("Lorem ipsum")
except:
  print("Something went wrong when writing to the file")
finally:
  f.close()


The program can continue, without leaving the file object open.


Raise an exception

As a Python developer you can choose to throw an exception if a condition occurs.

To throw (or raise) an exception, use the "raise" keyword.


Example

Raise an error and stop the program if x is lower than 0:

x = -1

if x < 0:
  raise Exception("Sorry, no numbers below zero")


The "raise" keyword is used to raise an exception.

You can define what kind of error to raise, and the text to print to the user.


Example

Raise a TypeError if x is not an integer:

x = "hello"

if not type(x) is int:
  raise TypeError("Only integers are allowed")


Python eval()

The eval() method parses the expression passed to this method and runs python expression (code) within the program.


In simple terms, the eval() method runs the python code (which is passed as an argument) within the program.

The syntax of eval() is:

eval(expression, globals=None, locals=None)


eval() Parameters

The eval() takes three parameters:

  • expression - this string as parsed and evaluated as a Python expression
  • globals (optional) - a dictionary
  • locals (optional)- a mapping object. Dictionary is the standard and commonly used mapping type in Python.

The use of "globals" and "locals" will be discussed later in this article.


Return Value from eval()

The eval() method returns the result evaluated from the "expression".


Example 1: How eval() works in Python?

x = 2
print(eval('x + 1'))

When you run the program, the output will be:

3

Here, the eval() evaluates the expression "x + 1" and print it.


Example 2: Practical Example to Demonstrate Use of eval()

# Calculate perimeter of square
def calPeri(L):
    return 4*L

# Calculate area of square
def calArea(L):
    return L*L

property = input("Type a function: ")

for L in range(1, 5):
    if (property == 'calPeri(L)'):
        print("If length is ", L, ", perimeter is ", eval(property), ".")
    elif (property == 'calArea(L)'):
        print("If length is ", L, ", area is ", eval(property), ".")
    else:
        print('Wrong Function')
        break


The output of the above program will be:

Type a function: calPeri(L)
If length is  1 , perimeter is  4 .
If length is  2 , perimeter is  8 .
If length is  3 , perimeter is  12 .
If length is  4 , perimeter is  16 .

or

Type a function: calArea(L)
If length is  1 , area is  1 .
If length is  2 , area is  4 .
If length is  3 , area is  9 .
If length is  4 , area is  16 .


Why you should be careful while using eval()?

Consider a situation, you are using a Unix system (macOS, Linux etc) and you have imported "os" module. The os module provides portable way to use operating system functionalities like: read or write a file.

If you allow users to input a value using "eval(input())", the user may issue commands to change file or even delete all the files using command "os.system('rm -rf *')".

https://www.programiz.com/python-programming/methods/built-in/eval

See also

References

  1. cite web | url=https://docs.python.org/library/tkinter.html | title=Tkinter — Python interface to Tcl/Tk — Python v2.6.1 documentation | accessdate=2009-03-12
  2. cite web | url=https://wiki.python.org/moin/TkInter | title= Tkinter - Pythoninfo Wiki
  3. citation | url=http://infohost.nmt.edu/tcc/help/pubs/tkinter/ | title=Tkinter reference: a GUI for Python | first=John W. | last=Shipman | publisher=New Mexico Tech Computer Center | date=2010-12-12 | accessdate=2012-01-11
  4. cite web |url=http://tkinter.unpythonic.net/wiki/Tkinter |title=Archived copy |accessdate=2013-11-13 |url-status=dead |archiveurl=https://web.archive.org/web/20131113222939/http://tkinter.unpythonic.net/wiki/Tkinter |archivedate=2013-11-13
  5. cite web | url=http://bugs.python.org/issue2983 | title=Python issue #2983, "Ttk support for Tkinter"
  6. cite web | url=http://svn.python.org/view?view=rev&revision=69051 | title=Python subversion revision 69051, which resolves issue #2983 by adding the ttk module
  7. cite web | url=http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/minimal-app.html | title=Tkinter 8.5 reference: a GUI for Python
  8. cite web |last1=Klein |first1=Bernd |title=GUI Programming with Python: Events and Binds |url=https://www.python-course.eu/tkinter_events_binds.php |website=www.python-course.eu |accessdate=18 August 2018
  9. cite web | url=https://www.python.org/dev/peps/pep-0397 | title=PEP 397 — Python launcher for Windows — Python.org | accessdate=2017-06-07

External links