Difference between revisions of "Tkinter"

Jump to navigation Jump to search
14,571 bytes added ,  21:43, 15 July 2021
no edit summary
 
(5 intermediate revisions by 4 users not shown)
Line 2: Line 2:
<div style="float: right; margin-left: 12px">__TOC__</div>
<div style="float: right; margin-left: 12px">__TOC__</div>


'''Tkinter''' is a [[Python (programming language)|Python]] [[Language binding|binding]] to the [[Tk (software)|Tk]] [[Graphical user interface|GUI]] toolkit. It is the standard [[Python]] interface to the Tk GUI toolkit,<ref>{{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}}</ref> and is Python's [[de facto standard|''de facto'' standard]] GUI.<ref>{{cite web | url=https://wiki.python.org/moin/TkInter | title= Tkinter - Pythoninfo Wiki}}</ref> Tkinter is included with standard [[Linux]], [[Microsoft Windows]] and [[Mac OS X]] installs of Python.
'''Tkinter''' is a [[Python (programming language)|Python]] [[Language binding|binding]] to the [[Tk (software)|Tk]] [[Graphical user interface|GUI]] toolkit. It is the standard [[Python]] interface to the Tk GUI toolkit,<ref>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</ref> and is Python's [[de facto standard|''de facto'' standard]] GUI.<ref>cite web | url=https://wiki.python.org/moin/TkInter | title= Tkinter - Pythoninfo Wiki</ref> 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.<ref>{{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}}</ref>


Tkinter is [[free software]] released under a [[Python license]].<ref>{{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 }}</ref>
The name ''Tkinter'' comes from ''Tk interface''. Tkinter was written by Fredrik Lundh.<ref>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</ref>
 
 
Tkinter is [[free software]] released under a [[Python license]].<ref>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</ref>




Line 23: Line 25:




Use [[VSCodium]] or any [[ource-code editor]] to edit your [[source code]]s.
Use [[VSCodium]] or any [[source-code editor]] to edit your [[source code]]s.




Line 29: Line 31:
You can execute your program like the below command.
You can execute your program like the below command.
  python3 cal.py
  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===
===[[WIMP (computing)|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.<ref>cite web | url=http://bugs.python.org/issue2983 | title=Python issue #2983, "Ttk support for Tkinter"</ref><ref>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</ref> 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 [https://infocode.org/?s=tkinter Tkinter] application with one widget:<ref>cite web | url=http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/minimal-app.html | title=Tkinter 8.5 reference: a GUI for Python</ref> (For Python 2, the only difference is the word "tkinter" in the import command will be capitalized to "[https://infocode.org/?s=tkinter 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. <ref name=klein>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</ref>
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]] [[Interpreter directive|directive]] to the program launcher, allowing the selection of an appropriate interpreter executable, when self-executing.<ref>cite web | url=https://www.python.org/dev/peps/pep-0397 | title=PEP 397 — Python launcher for Windows — Python.org | accessdate=2017-06-07</ref>
*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" ==
== Elements arrangement by using "pack" and "grid" ==
Line 105: Line 198:
  btn_2.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".
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 ==
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]]
[[GUI]] calculator [[source code]]


  <nowiki>''' cal.py</nowiki>
  <nowiki>''' cal.py</nowiki>
Line 144: Line 248:
             # partial takes care of function and argument
             # partial takes care of function and argument
             cmd = partial(self.calculate, b)
             cmd = partial(self.calculate, b)
             tk.Button(self, text=b, width=5, relief=rel,
             tk.Button(self, text=b, width=5, relief=rel, command=cmd).grid(row=r, column=c)
                command=cmd).grid(row=r, column=c)
             c += 1
             c += 1
             if c > 4:
             if c > 4:
Line 194: Line 297:
  app.mainloop()
  app.mainloop()


 
=== General explanation for the source code ===
=== Explanation of the source code ===
The below link is the origin of the [[source code]].
The below link is the origin of the [[source code]].


Line 244: Line 346:
Under MyApp [[class]], there are three [[function]]s defined by "def". [[Definition]] is different to [[declaration]].
Under MyApp [[class]], there are three [[function]]s defined by "def". [[Definition]] is different to [[declaration]].


==Description==
=== Make a blank window ===
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.
 
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.
 


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


===Some definitions===
Example 2: Practical Example to Demonstrate Use of eval()


===[[WIMP (computing)|Window]]===
# Calculate perimeter of square
This term has different meanings in different contexts, but in general it refers to a rectangular area somewhere on the user's display screen.
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


===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 output of the above program will be:
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.<ref>{{cite web | url=http://bugs.python.org/issue2983 | title=Python issue #2983, "Ttk support for Tkinter" }}</ref><ref>{{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}}</ref> 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===
Type a function: calPeri(L)
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.
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 .


===Child and parent===
or
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==
Type a function: calArea(L)
Here is a minimal Python 3 [https://infocode.org/?s=tkinter Tkinter] application with one widget:<ref>{{cite web | url=http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/minimal-app.html | title=Tkinter 8.5 reference: a GUI for Python }}</ref> (For Python 2, the only difference is the word "tkinter" in the import command will be capitalized to "[https://infocode.org/?s=tkinter Tkinter].")
If length is  1 , area is  1 .
<source lang="python" line="1">
If length is  2 , area is  4 .
#!/usr/bin/env python3
If length is  3 , area is  9 .
from tkinter import *
If length is  4 , area is  16 .
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><ref>{{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}}</ref>
===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. <ref name=klein>{{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}}</ref>
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">
#!/usr/bin/env python3
import tkinter as tk


class Application(tk.Frame):


    def __init__(self, master=None):
Why you should be careful while using eval()?
        tk.Frame.__init__(self, master)
        self.grid() 
        self.createWidgets()


    def createWidgets(self):
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.
        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()
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 *')".
app.master.title('Sample application')
app.mainloop()
</source>


*line 1: [[Hashbang]] [[Interpreter directive|directive]] to the program launcher, allowing the selection of an appropriate interpreter executable, when self-executing.<ref>{{cite web | url=https://www.python.org/dev/peps/pep-0397 | title=PEP 397 — Python launcher for Windows — Python.org | accessdate=2017-06-07}}</ref>
https://www.programiz.com/python-programming/methods/built-in/eval
*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 ==
== See also ==
Line 340: Line 890:
* [[Programmer]], a person who writes software
* [[Programmer]], a person who writes software
* [[I2P]]
* [[I2P]]
* [[Unix]] ([[UNIX]])
:* [[BSD]] ([[Berkeley Software Distribution]])
::* [[macOS]] ([[Mac OS X]], [[OS X]])
:* [[Linux]]
* [[Windows]] ([[Microsoft Windows]])
* [[Artificial intelligence]]
:* [[Statistics]]
:* [[Machine learning]]


== References ==
== References ==
Line 352: Line 910:
[[Category:Python libraries]]
[[Category:Python libraries]]
[[Category:Tk (software)]]
[[Category:Tk (software)]]
[[Category:Python]]
[[Category:Tkinter]]
5

edits

Navigation menu