Python3 Previous version with Tkinter, followed by Tkinter
The simplest code to use Tkinter is to first create a window of TK () and then add the various widgets
From Tkinter Import *window = Tk () label = label (window, Text = "Welcome to Python") button = button (window, Text = "click M E ") Label.pack () Button.pack () Window.mainloop ()
Tkinter programming is event-driven, and when a button is clicked, the event can be handled by a function
From Tkinter import *def Processok (): print ("OK") def processcancel (): print ("Cancel") window = Tk () Btok = Button (window, Text = "OK", FG = "Red", command = processok) btcancel = button (window, text = "Cancel", bg = "yellow", command = Processcancel) Btok.pack () Btcancel.pack () Window.mainloop ()
Where the parameter command is the bound function
There are also a variety of widgets available Classes
- Button
- Canvas
- Checkbutton
- Entry
- Frame
- Label
- Menu
- Menubutton
- Message
- Radiobutton
- Text
You can modify one of the Widget's properties directly:
btshoworhide = button (window, text = "Show", bg = "white") btshoworhide["text"] = "Hide" btshoworhide["bg"] = "Red" Btshoworh Ide["FG"] = "#AB84F9" # change FG color to #AB84F9btShowOrHide ["cursor"] = "plus" # change mouse cursor to Plusbtshoworhid E["justify"] = left # Set justify to left
Intvar (), Stringvar ()
From Tkinter import *class widgetsdemo:def __init__ (self): window = Tk () window.title (' Widgets Demo ') frame1 = Frame (window) frame1.pack () self.v1 = Intvar () self.v2 = Intvar () rbred = Radiobutton (frame1, Text = "Red", BG = "Red", variable = self.v2, value = 1, command = Self.processradiobutton) r Byellow = Radiobutton (frame1, Text = "Yellow", bg = "Yellow", variable = self.v2, value = 2, command = Self.processradiobu Tton) Rbred.grid (row = 1, column = 2) rbyellow.grid (row = 1, column = 3) frame2 = Frame (windo W) frame2.pack () label = label (frame2, Text = "Enter Your Name:") Self.name = Stringvar () en Tryname = Entry (frame2, textvariable = self.name) btgetname = button (frame2, Text = "Get name", command = Self.proc Essbutton) message = Message (frame2, Text = "It is a widgets demo") Label.grid (row = 1, column = 1) E Ntryname.grid (row = 1, cOlumn = 2) btgetname.grid (row = 1, column = 3) message.grid (row = 1, column = 4) window.mainl OOP () def Processradiobutton (self): print (("Red" if self.v2.get () = = 1 Else "Yellow") + "is selected") def Processbutton (self): print ("Your name is" + self.name.get ()) Widgetsdemo ()
The keys of the two colors in the above code are bound to the Intvar () type variable, assigning values of 1 and 2 respectively, then the value of Intvar () can be obtained with get (), while the input text window binds the string variable stringvar ()
Canvas: Can be used to show some graphics
From Tkinter import *class canvasdemo: def __init__ (self): window = Tk () window.title ("Canvas demo") Self.canvas = canvas (window, width = max, height = +, bg = "white") Self.canvas.pack () frame = frame (window)
frame.pack () btrectangle = button (frame, text = "Tectangle", command = self.displayrect) btrectangle.grid (row = 1, column = 1) Window.mainloop () def displayrect (self): self.canvas.create_rectangle (10, 10, 190, 90, tags = "rect") Canvasdemo ()
Menus
menubar = menu (window) window.config (menu = menubar) # Display the menu Baroperationmenu = Menu (menubar, tearoff = 0) Menuba R.add_cascade (label = "Operation", menu = operationmenu) # header Operationmenu.add_command (label = "Add", command = Self.add) Operationmenu.add_command (...) # add menu option Exitmenu = Menu (menubar, tearoff = 0) menubar.add_cascade (label = "Exit", menu = Exi Tmenu) exitmenu.add_command (label = "Quit", command = window.quit)
Popup Menus
From Tkinter import *class popupmenudemo: def __init__ (self): window = Tk () window.title ("popup Menu Demo") Self.menu = menu (window, tearoff = 0) self.menu.add_command (label = "Draw a line", command = self.displayline)
self.menu.add_command (label = "Draw an oval", command = ...) def displayline (self): ...
Mouse, Key events, and Bindings
Widget.bind (event, handler)}}}{{{class = "Brush:python" Def popup (Event): menu.post (Event.x_root,event.y_root)
Event |
Description |
<Bi-Motion> |
An event occurs if a mouse button is moved and being held down on the widget. |
<Button-i> |
Button-1, Button-2, and Button-3 identify the left, middle, and right buttons. When a mouse button was pressed over the widget, Tkinter automatically grabs the mouse pointer's location. Buttonpressed-i is synonymous with button-i. |
<ButtonReleased-i> |
An event occurs if a mouse button is released. |
<Double-Button-i> |
An event occurs if a mouse button is double-clicked. |
<Enter> |
An event occurs when a mouse pointer enters the widget. |
<Key> |
An event occurs if a key is pressed. |
<Leave> |
An event occurs when a mouse pointer leaves the widget. |
<Return> |
An event occurs when the Enter key is pressed. You can bind any key such as A, B, up, down, left, right in the keyboard with an event. |
<Shift+A> |
An event occurs when the Shift+a keys is pressed. You can combine Alt, Shift, and Control with the other keys. |
<Triple-Button-i> |
An event occurs if a mouse button is triple-clicked. |
Event Properties
Event Properties |
Description |
char |
the CH Aracter entered from the keyboard for key events. |
keycode |
the key code (i.e, Unicode) for the key entered from the keyboard for key events. |
keysym |
the key symbol (i.e., character) for the key entered from the keyboard for Key events. |
num |
the button number (1, 2, 3) indicates which mouse button was clicked. |
widget |
The Widget object that fires this event. |
x and y |
the current mouse location in the widgets in pixels. |
x_ root and Y_root |
the current mouse position relative to the upper-left corner of the SCR Een, in pixels. |
From Tkinter import *class mousekeyeventdemo: def __init__ (self): window = Tk () Window.title ("event demo") canvas = canvas (window, BG = "white", width = max, height = +) canvas.pack () # Bind with <Button-1> E Vent canvas.bind ("<Button-1>", self.processmouseevent) # Bind with <Key> event Canvas.bind ( "<Key>", Self.processkeyevent) Canvas.focus_set () # set keyboard focus Window.mainloop () def on this window Processmouseevent (self, event): print ("clicked at", Event.x, Event.y) # Coordinates in the current window print ("position in the Screen ", Event.x_root, Event.y_root) # The coordinates print in the entire display (" which button is clicked? ", Event.num) def Processkeyevent (self, event): Print (" keysym?", Event.keysym) print (" char?", Event.char) print (" KeyCode? ", Event.keycode) Mousekeyeventdemo ()
Operation Result:
(' clicked at ', 109, 53) (' position in the screen ', 908, 105) (' Which button is clicked? ', 1) (' Keysym? ', ' shift_l ') (' char? ', ') (' KeyCode? ', 50)
Animations
# coding:utf-8from Tkinter Import *class animationdemo: def __init__ (self): window = Tk () window.title (" Event Demo ") width = # width canvas = canvas (window, BG =" white ", Width = width, height =) canvas.pack () x = 0 # initial position Canvas.create_text (x, 3, Text = "message moving?", tags = "text") dx = # each move distance while T Rue: canvas.move ("text", DX, 0) canvas.after (100) # Stop 100 ms canvas.update () if x < width: x + = dx else: x = 0 canvas.delete ("text") canvas.create_text (x, page, Text = "message moving?", tags = "text") Window.mainloop () Animationdemo ()
Scrollbars
ScrollBar = ScrollBar (frame) scrollbar.pack (side = right, fill = Y) Text = text (frame, wrap = WORD, Yscrollcommand = scrollb Ar.set) Text.pack () scrollbar.config (command = Text.yview)
Standard Dialog Boxes
#coding: Utf-8import tkcolorchooserimport tkmessageboximport tksimpledialogtkmessagebox.showinfo ("Hello", "some info ") tkmessagebox.showwarning (title, message) Tkmessagebox.showerror (title, message) Isyes = Tkmessagebox.askyesno (" AskYesNo "," Continue? ") Print (isyes) name = tksimpledialog.askstring ("askstring", "Your name?") Print (name) height = tksimpledialog.askfloat ("Askfloat", "your height?") Print (height)