Tkinter - RIP Tutorial

3y ago
206 Views
16 Downloads
1,004.85 KB
35 Pages
Last View : 16d ago
Last Download : 2m ago
Upload by : Gia Hauser
Transcription

tkinter#tkinter

Table of ContentsAbout1Chapter 1: Getting started with tkinter2RemarksDifferences between python 2 and 322Importing in python 2.x2Importing in python 3.x2Further Reading2Versions3Tcl3Python3Examples4Installation or Setup4Hello, World! (minimal)5Hello, World! (modular, object-oriented)6Chapter 2: Adding Images To Label/Button8Introduction8Examples8File Formats Supported By Tkinter8Usage of .GIF formats.8Chapter 3: Customize ttk styles9Introduction9Examples9Customize a treeviewChapter 4: Delaying a .after()11Chapter 5: Multiple windows (TopLevel widgets)13

Examples13Difference between Tk and Toplevel13arranging the window stack (the .lift method)14Chapter 6: Scrolling 16Examples16Connecting a vertical scrollbar to a Text widget16Scrolling a Canvas widget horizontally and vertically16Scrolling a group of widgets17Chapter 7: The Tkinter Entry ating an Entry widget and setting a default value18Getting the value of an Entry widget18Adding validation to an Entry widget19Getting int From Entry Widget19Chapter 8: The Tkinter Radiobutton e's an example of how to turn radio buttons to button boxes:21Create a group of radiobuttons21Chapter 9: Tkinter Geometry Managers22Introduction22Examples22pack()22

grid()23place()24Chapter 10: Ttk 27Examples27Treeview: Basic example27Create the widget27Definition of the columns27Definition of the headings28Insert some rows28Packing28Progressbar29Function updating the progressbar29Set the maximum value29Create the progress bar29Initial and maximum values29Emulate progress each 0.5 s29Credits31

AboutYou can share this PDF with anyone you feel could benefit from it, downloaded the latest versionfrom: tkinterIt is an unofficial and free tkinter ebook created for educational purposes. All the content isextracted from Stack Overflow Documentation, which is written by many hardworking individuals atStack Overflow. It is neither affiliated with Stack Overflow nor official tkinter.The content is released under Creative Commons BY-SA, and the list of contributors to eachchapter are provided in the credits section at the end of this book. Images may be copyright oftheir respective owners unless otherwise specified. All trademarks and registered trademarks arethe property of their respective company owners.Use the content presented in this book at your own risk; it is not guaranteed to be correct noraccurate, please send your feedback and corrections to info@zzzprojects.comhttps://riptutorial.com/1

Chapter 1: Getting started with tkinterRemarksTkinter ("Tk Interface")is python's standard cross-platform package for creating graphical userinterfaces (GUIs). It provides access to an underlying Tcl interpreter with the Tk toolkit, which itselfis a cross-platform, multilanguage graphical user interface library.Tkinter isn't the only GUI library for python, but it is the one that comes standard. Additional GUIlibraries that can be used with python include wxPython, PyQt, and kivy.Tkinter's greatest strength is its ubiquity and simplicity. It works out of the box on most platforms(linux, OSX, Windows), and comes complete with a wide range of widgets necessary for mostcommon tasks (buttons, labels, drawing canvas, multiline text, etc).As a learning tool, tkinter has some features that are unique among GUI toolkits, such as namedfonts, bind tags, and variable tracing.Differences between python 2 and 3Tkinter is largely unchanged between python 2 and python 3, with the major difference being thatthe tkinter package and modules were renamed.Importing in python 2.xIn python 2.x, the tkinter package is named Tkinter, and related packages have their own names.For example, the following shows a typical set of import statements for python 2.x:import Tkinter as tkimport tkFileDialog as filedialogimport ttkImporting in python 3.xAlthough functionality did not change much between python 2 and 3, the names of all of the tkintermodules have changed. The following is a typical set of import statements for python 3.x:import tkinter as tkfrom tkinter import filedialogfrom tkinter import ttkFurther Readinghttps://riptutorial.com/2

Tkinter questions on StackoverflowOfficial Python 3 tkinter documentationOfficial Python 2 tkinter documentationTkdocs.com - multiplatform tk documentationEffbot introduction to tkinterTkinter reference guide, New Mexico TechVersionsTclVersionRelease nVersionRelease 10-07-03https://riptutorial.com/3

VersionRelease lesInstallation or SetupTkinter comes pre-installed with the Python installer binaries for Mac OS X and the Windowsplatform. So if you install Python from the official binaries for Mac OS X or Windows platform, youare good to go with Tkinter.For Debian versions of Linux you have to install it manually by using the following commands.For Python 3sudo apt-get install python3-tkFor Python 2.7sudo apt-get install python-tkLinux distros with yum installer can install tkinter module using the command:yum install tkinterVerifying InstallationTo verify if you have successfully installed Tkinter, open your Python console and type thefollowing command:import tkinter as tk # for Python 3 versionorimport Tkinter as tk # for Python 2.x versionhttps://riptutorial.com/4

You have successfully installed Tkinter, if the above command executes without an error.To check the Tkinter version, type the following commands in your Python REPL:For python 3.Ximport tkinter as tktk. test()For python 2.Ximport Tkinter as tktk. test()Note: Importing Tkinterbetween version.as tkis not required but is good practice as it helps keep things consistentHello, World! (minimal)Let's test our basic knowledge of tkinter by creating the classic "Hello, World!" program.First, we must import tkinter, this will vary based on version (see remarks section about"Differences between Python 2 and 3")In Python 3 the module tkinter has a lowercase t:import tkinter as tkIn Python 2 the module Tkinter has a uppercase T:import Tkinter as tkUsing as tk isn't strictly necessary but we will use it so the rest of this example will work the samefor both version.now that we have the tkinter module imported we can create the root of our application using theTk class:root tk.Tk()This will act as the window for our application. (note that additional windows should be Toplevelinstances instead)Now that we have a window, let's add text to it with a Labellabel tk.Label(root, text "Hello World!") # Create a text labellabel.pack(padx 20, pady 20) # Pack it into the windowOnce the application is ready we can start it (enter the main event loop) with the mainloop methodhttps://riptutorial.com/5

root.mainloop()This will open and run the application until it is stopped by the window being closed or callingexiting functions from callbacks (discussed later) such as root.destroy().Putting it all together:import tkinter as tk # Python 3.x Version#import Tkinter as tk # Python 2.x Versionroot tk.Tk()label tk.Label(root, text "Hello World!") # Create a text labellabel.pack(padx 20, pady 20) # Pack it into the windowroot.mainloop()And something like this should pop up:Hello, World! (modular, object-oriented)import tkinter as tkclass HelloWorld(tk.Frame):def init (self, parent):super(HelloWorld, self). init (parent)self.label tk.Label(self, text "Hello, World!")self.label.pack(padx 20, pady 20)if name " main ":root tk.Tk()main HelloWorld(root)main.pack(fill "both", expand True)root.mainloop()Note: It's possible to inherit from just about any tkinter widget, including the root window. Inheritingfrom tkinter.Frame is at least arguably the most flexible in that it supports multiple documentinterfaces (MDI), single document interfaces (SDI), single page applications, and multiple-pagehttps://riptutorial.com/6

applications.Read Getting started with tkinter online: started-withtkinterhttps://riptutorial.com/7

Chapter 2: Adding Images To Label/ButtonIntroductionThis shows the proper usage of images and how to correctly display images.ExamplesFile Formats Supported By TkinterTkinter support .ppm files from PIL(Python Imaging Library), .JPG, .PNG and .GIF.To import and image you first need to create a reference like so:Image PhotoImage(filename [Your Image here])Now, we can add this image to Button and Labels like so using the "img" callback:Lbl Label (width 490, img image)Usage of .GIF formats.In order to display a gif, you need to show it frame by frame sort of like an animation.An animated gif consists of a number of frames in a single file. Tk loads the first frame but you canspecify different frames by passing an index parameter when creating the image. For example:frame2 PhotoImage(file imagefilename, format "gif -index 2")If you load up all the frames into separate PhotoImages and then use timer events to switch theframe being shown (label.configure(image nextframe)). The delay on the timer lets you control theanimation speed. There is nothing provided to give you the number of frames in the image otherthan it failing to create a frame once you exceed the frame count.Read Adding Images To Label/Button online: mages-to-label-buttonhttps://riptutorial.com/8

Chapter 3: Customize ttk stylesIntroductionThe style of the new ttk widgets is one of the most powerful aspects of ttk. Besides the fact that itis a completely different way of working than the traditional tk package, it enables to perform ahuge degree of customization on your widgets.ExamplesCustomize a treeviewBy taking Treeview: Basic example, it can be shown how to customize a basic treeview.In this case, we create a style "mystyle.Treeview" with the following code (see the comments tounderstand what each line does):style ttk.Style()style.configure("mystyle.Treeview", highlightthickness 0, bd 0, font ('Calibri', 11)) # Modifythe font of the bodystyle.configure("mystyle.Treeview.Heading", font ('Calibri', 13,'bold')) # Modify the font ofthe headingsstyle.layout("mystyle.Treeview", [('mystyle.Treeview.treearea', {'sticky': 'nswe'})]) # Removethe bordersThen, the widget is created giving the above style:tree ttk.Treeview(master,style "mystyle.Treeview")If you would like to have a different format depending on the rows, you can make use of tags:tree.insert(folder1, "end", "", text "photo1.png", values ("23-Jun-17 11:28","PNG file","2.6KB"),tags ('odd',))tree.insert(folder1, "end", "", text "photo2.png", values ("23-Jun-17 11:29","PNG file","3.2KB"),tags ('even',))tree.insert(folder1, "end", "", text "photo3.png", values ("23-Jun-17 11:30","PNG file","3.1KB"),tags ('odd',))Then, for instance, a background color can be associated to the tags:tree.tag configure('odd', background '#E8E8E8')tree.tag configure('even', background '#DFDFDF')The result is a treeview with modified fonts on both the body and headings, no border and differentcolors for the rows:https://riptutorial.com/9

Note: To generate the above picture, you should add/change the aforementioned lines of code inthe example Treeview: Basic example.Read Customize ttk styles online: ize-ttk-styleshttps://riptutorial.com/10

Chapter 4: Delaying a functionSyntax widget.after(delay ms, callback, *args)ParametersParameterDescriptiondelay msTime (milliseconds) which is delayed the call to the function callbackcallbackFunction that is called after the given delay ms. If this parameter is not given,.after acts similar to time.sleep (in milliseconds)RemarksSyntax assumes a widget accepted by the method .after has been previously created (i.ewidget tk.Label(parent))Examples.after()is a method defined for all tkinter widgets. This method simply callsthe function callback after the given delay in ms. If no function is given, it acts similar to time.sleep(but in milliseconds instead of seconds).after(delay, callback None)Here is an example of how to create a simple timer using after:# import tkintertry:import tkinter as tkexcept ImportError:import Tkinter as tkclass Timer:def init (self, parent):# variable storing timeself.seconds 0# label displaying timeself.label tk.Label(parent, text "0 s", font "Arial 30", width 10)self.label.pack()# start the timerself.label.after(1000, self.refresh label)def refresh label(self):https://riptutorial.com/11

""" refresh the content of the label every second """# increment the timeself.seconds 1# display the new timeself.label.configure(text "%i s" % self.seconds)# request tkinter to call self.refresh after 1s (the delay is given in ms)self.label.after(1000, self.refresh label)if name " main ":root tk.Tk()timer Timer(root)root.mainloop()Read Delaying a function online: g-a-functionhttps://riptutorial.com/12

Chapter 5: Multiple windows (TopLevelwidgets)ExamplesDifference between Tk and Toplevelis the absolute root of the application, it is the first widget that needs to be instantiated and theGUI will shut down when it is destroyed.Tkis a window in the application, closing the window will destroy all children widgets placedon that window{1} but will not shut down the program.Topleveltry:import tkinter as tk #python3except ImportError:import Tkinter as tk #python2#root application, can only have one of these.root tk.Tk()#put a label in the root to identify th

Tkinter ("Tk Interface")is python's standard cross-platform package for creating graphical user interfaces (GUIs). It provides access to an underlying Tcl interpreter with the Tk toolkit, which itself is a cross-platform, multilanguage graphical user interface library. Tkinter isn't the only GUI library for python, but it is the one that comes standard. Additional GUI libraries that can be .

Related Documents:

Python 1 and 2; renamed to tkinter in Python 3). If Tkinter is available, then no errors occur, as demonstrated in the following: import tkinter If your Python interpreter was not compiled with Tkinter enabled, the module import fails. You might need to recompile your Python interpreter to gain access to Tkinter. This usually

In addition to the Tk interface module, Tkinter includes a number of Python modules. The two most important modules are the Tkinter module itself, and a module called Tkconstants. The former automatically imports the latter, so to use Tkinter, all you need to do is to import one module: import Tkinter Or,

Tkinter is largely unchanged between python 2 and python 3, with the major difference being that the tkinter package and modules were renamed. Importing in python 2.x In python 2.x, the tkinter package is named Tkinter, and related packages have their own names. For example, the following shows a typical set of import statements for python 2.x:

11 am - Bernie O'Malley, RIP Kevin O'Brien, RIP 5 pm - Gary Gilliland, RIP Mon. April 19th - 9 am - John Blair, Jr., RIP Tues. April 20th - 9 am - Michael & Gwen LaHair, RIP Wed. April 21st - 9 am - Anthony Dunn Thurs. April 22nd - 9 am - David Acevedo, RIP Fri. April 23rd - 9 am - Edmund Kelly, RIP Sat. April 24th - 9 am - Louis White, RIP

Rip Van Winkle! Rip Van Winkle! NARRATOR: Rip looked all around but could see no one. RIP: Did you hear that, boy? STRANGER: (distantly yelling) Rip Van Winkle! Rip Van Winkle! WOLF: Grrrr. NARRATOR: Wolf bristled up his back, looking down the valley. Then Rip saw a strange figure slowly toiling up the side of

"Tkinter is Python's de facto standard GUI (Graphical User Interface) package. It is a thin object oriented layer on top of Tcl/Tk." Tkinter examples you may have seen. Tkinter examples you may have seen. With ttk, you get a nicer look. Themed widgets can match the platform. .

Setup Begin with this import statement: from tkinter import * Note: In earlier versions of Python, this module was called Tkinter, not tkinter Then create an object of type Tk: top Tk() This is the top-level window of your GUI program You can use any name for it; in these slide

EMC Overview 43 Immunity Issues Can Exist Due To The Following Most of today’s electrical and electronic systems rely on active devices such as microprocessors and digital logic for: –Control of system functions. –User convenience / features. –Legislated system requirements (such as mobile telephone location reporting). With today’s vast networks for data communication there .