In [7]:
from tkinter import * # Import tkinter
    
class GridManagerDemo:
    window = Tk() # Create a window
    window.title("Grid Manager Demo") # Set title
    
    message = Message(window, text = 
        "This Message widget occupies three rows and two columns")
    message.grid(row = 1, column = 1, rowspan = 5, columnspan = 2)
    Label(window, text = "First Name:").grid(row = 1, column = 3)
    Entry(window).grid(row = 1, column = 4, padx = 5, pady = 5)
    Label(window, text = "Last Name:").grid(row = 2, column = 3)
    Entry(window).grid(row = 2, column = 4)
    Button(window, text = "Get Name").grid(row = 3, 
        padx = 5, pady = 5, column = 4, sticky = W)
    
    window.mainloop() # Create an event loop

GridManagerDemo() # Create GUI 
Out[7]:
<__main__.GridManagerDemo at 0x1792ad9dd00>
In [8]:
import tkinter as tk

colours = ['red','green','orange','white','yellow','blue']

r = 0
for c in colours:
    tk.Label(text=c, relief=tk.RIDGE, width=15).grid(row=r,column=0)
    tk.Entry(bg=c, relief=tk.SUNKEN, width=10).grid(row=r,column=1)
    r = r + 1

tk.mainloop()
In [12]:
import tkinter
root = tkinter.Tk(  )
for r in range(6):
   for c in range(6):
      tkinter.Label(root, text='R%s/C%s'%(r,c), borderwidth=3, padx=8, pady=8, fg="yellow", bg="blue" ).grid(row=r,column=c)
root.mainloop()
In [16]:
import tkinter
from tkinter import messagebox

top = tkinter.Tk()
top.geometry("400x600") #Width x Height

def helloCallBack():
   messagebox.showinfo( "Hello Python", "Hello World")

B = tkinter.Button(top, text ="Hello", command = helloCallBack)

B.pack()
B.place(bordermode="outside", height=200, width=200)
top.mainloop()
In [21]:
import tkinter as tk
import random

root = tk.Tk()
# width x height + x_offset + y_offset:
# geometry("window width x window height + position right + position down")
# position the top left corner of the window right 300 pixels and down 300 pixels.
root.geometry("170x200+30+230")

languages = ['Python', 'Perl', 'C++', 'Java', 'Tcl/Tk']
labels = range(5)
for i in range(5):
    ct = [random.randrange(256) for x in range(3)]
    print(ct)
    brightness = int(round(0.299 * ct[0] + 0.587 * ct[1] + 0.114 * ct[2]))
    ct_hex = "%02x%02x%02x" % tuple(ct)
    print(ct_hex)
    bg_colour = '#' + "".join(ct_hex)
    l = tk.Label(root,
                 text=languages[i],
                 fg='White' if brightness < 120 else 'Black',
                 bg=bg_colour)
    l.place(x=20, y=30 + i * 30, width=220, height=25)

root.mainloop() 
[199, 195, 180]
c7c3b4
[172, 153, 44]
ac992c
[29, 179, 93]
1db35d
[69, 151, 201]
4597c9
[228, 125, 97]
e47d61
In [22]:
import tkinter

window = tkinter.Tk()
window.title("GUI")

# creating a function called say_hi()
def say_hi():
    tkinter.Label(window, text = "Hi").pack()

# 'command' is executed when you click the button
# in this above case we're calling the function 'say_hi'.
tkinter.Button(window, text = "Click Me!", command = say_hi).pack() 
window.mainloop()
In [23]:
import tkinter

window = tkinter.Tk()
window.title("GUI")

#creating 3 different functions for 3 events
def left_click(event):
    tkinter.Label(window, text = "Left Click!").pack()

def middle_click(event):
    tkinter.Label(window, text = "Middle Click!").pack()

def right_click(event):
    tkinter.Label(window, text = "Right Click!").pack()

window.bind("<Button-1>", left_click)
window.bind("<Button-2>", middle_click)
window.bind("<Button-3>", right_click)

window.mainloop()
In [24]:
import tkinter

class GeeksBro:

    def __init__(self, window):
         # create a button to call a function called 'say_hi'
        self.text_btn = tkinter.Button(window, text = "Click Me!", command = self.say_hi)
        self.text_btn.pack()
        # closing the 'window' when you click the button
        self.close_btn = tkinter.Button(window, text = "Close", command = window.quit)
        self.close_btn.pack()

    def say_hi(self):
        tkinter.Label(window, text = "Hi").pack()

window = tkinter.Tk()
window.title("GUI")

geeks_bro = GeeksBro(window)

window.mainloop()
In [3]:
from tkinter import * # Import tkinter

def processOK():
    print("OK button is clicked")
 
def processCancel():
    print("Cancel button is clicked")
    
root = Tk() # Create a root window
btOK = Button(root, text = "OK", fg = "red", command = processOK) 
btCancel = Button(root, text = "Cancel", bg = "yellow", 
                  command = processCancel) 
btOK.pack() # Place the button in the window
btCancel.pack() # Place the button in the window

root.mainloop() # Create an event loop
OK button is clicked
OK button is clicked
OK button is clicked
Cancel button is clicked
Cancel button is clicked
Cancel button is clicked
Cancel button is clicked
Cancel button is clicked
In [5]:
from tkinter import * # Import tkinter
    
class WidgetsDemo:
    def __init__(self):
        window = Tk() # Create a window
        window.title("Widgets Demo") # Set a title
        
        # Add a button, a check button, and a radio button to frame1
        frame1 = Frame(window) # Create and add a frame to window
        frame1.pack()      
        self.v1 = IntVar()
        cbtBold = Checkbutton(frame1, text = "Bold", 
            variable = self.v1, command = self.processCheckbutton) 
        self.v2 = IntVar()
        rbRed = Radiobutton(frame1, text = "Red", bg = "red",
                variable = self.v2, value = 1, 
                command = self.processRadiobutton) 
        rbYellow = Radiobutton(frame1, text = "Yellow", 
                bg = "yellow", variable = self.v2, value = 2, 
                command = self.processRadiobutton) 
        cbtBold.grid(row = 1, column = 1)
        rbRed.grid(row = 1, column = 2)
        rbYellow.grid(row = 1, column = 3)
        
        # Add a button, a check button, and a radio button to frame1
        frame2 = Frame(window) # Create and add a frame to window
        frame2.pack()
        label = Label(frame2, text = "Enter your name: ")
        self.name = StringVar()
        entryName = Entry(frame2, textvariable = self.name) 
        btGetName = Button(frame2, text = "Get Name", 
            command = self.processButton)
        message = Message(frame2, text = "It is a widgets demo")
        label.grid(row = 1, column = 1)
        entryName.grid(row = 1, column = 2)
        btGetName.grid(row = 1, column = 3)
        message.grid(row = 1, column = 4)
        
        # Add a text
        text = Text(window) # Create a text add to the window
        text.pack()
        text.insert(END, 
            "Tip\nThe best way to learn Tkinter is to read ")
        text.insert(END, 
            "these carefully designed examples and use them ")
        text.insert(END, "to create your applications.")
        
        window.mainloop() # Create an event loop

    def processCheckbutton(self):
        print("check button is " 
            + ("checked " if self.v1.get() == 1 else "unchecked"))
        
    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() # Create GUI
check button is checked 
check button is unchecked
Red is selected 
Yellow is selected 
Your name is Selim
Red is selected 
Yellow is selected 
Red is selected 
check button is checked 
Your name is Selim
Out[5]:
<__main__.WidgetsDemo at 0x1cb3d1720d0>
In [6]:
from tkinter import * # Import tkinter
    
class CanvasDemo:
    def __init__(self):
        window = Tk() # Create a window
        window.title("Canvas Demo") # Set title
        
        # Place self.canvas in the window
        self.canvas = Canvas(window, width = 200, height = 100, 
            bg = "white")
        self.canvas.pack()
        
        # Place buttons in frame
        frame = Frame(window)
        frame.pack()
        btRectangle = Button(frame, text = "Rectangle", 
            command = self.displayRect)
        btOval = Button(frame, text = "Oval", 
            command = self.displayOval)
        btArc = Button(frame, text = "Arc", 
            command = self.displayArc)
        btPolygon = Button(frame, text = "Polygon", 
            command = self.displayPolygon)
        btLine = Button(frame, text = "Line", 
            command = self.displayLine)
        btString = Button(frame, text = "String", 
            command = self.displayString)
        btClear = Button(frame, text = "Clear", 
            command = self.clearCanvas)
        btRectangle.grid(row = 1, column = 1)
        btOval.grid(row = 1, column = 2)
        btArc.grid(row = 1, column = 3)
        btPolygon.grid(row = 1, column = 4)
        btLine.grid(row = 1, column = 5)
        btString.grid(row = 1, column = 6)
        btClear.grid(row = 1, column = 7)
        
        window.mainloop() # Create an event loop

    # Display a rectangle
    def displayRect(self):
        self.canvas.create_rectangle(10, 10, 190, 90, tags = "rect")
        
    # Display an oval
    def displayOval(self):
        self.canvas.create_oval(10, 10, 190, 90, fill = "red", 
            tags = "oval")
    
    # Display an arc
    def displayArc(self):
        self.canvas.create_arc(10, 10, 190, 90, start = 0, 
            extent = 90, width = 8, fill = "red", tags = "arc")
    
    # Display a polygon
    def displayPolygon(self):
        self.canvas.create_polygon(10, 10, 190, 90, 30, 50, 
            tags = "polygon")
    
    # Display a line
    def displayLine(self):
        self.canvas.create_line(10, 10, 190, 90, fill = "red", 
            tags = "line")
        self.canvas.create_line(10, 90, 190, 10, width = 9, 
            arrow = "last", activefill = "blue", tags = "line")
    
    # Display a string
    def displayString(self):
        self.canvas.create_text(60, 40, text = "Hi, I am a string", 
           font = "Times 10 bold underline", tags = "string")
    
    # Clear drawings
    def clearCanvas(self):
        self.canvas.delete("rect", "oval", "arc", "polygon", 
            "line", "string")

CanvasDemo() # Create GUI 
Out[6]:
<__main__.CanvasDemo at 0x1cb3bf66f40>
In [8]:
from tkinter import * # Import tkinter
    
class PlaceManagerDemo:
    def __init__(self):
        window = Tk() # Create a window
        window.title("Place Manager Demo") # Set title
        
        Label(window, text = "Blue", bg = "blue").place(
            x = 120, y = 20)
        Label(window, text = "Red", bg = "red").place(
            x = 50, y = 50)
        Label(window, text = "Green", bg = "green").place(
            x = 80, y = 80)
        
        window.mainloop() # Create an event loop

PlaceManagerDemo() # Create GUI 
Out[8]:
<__main__.PlaceManagerDemo at 0x1cb3daab7c0>
In [9]:
from tkinter import * # Import tkinter
    
class LoanCalculator:
    def __init__(self):
        window = Tk() # Create a window
        window.title("Loan Calculator") # Set title
        
        Label(window, text = "Annual Interest Rate").grid(row = 1, 
            column = 1, sticky = W)
        Label(window, text = "Number of Years").grid(row = 2, 
            column = 1, sticky = W)
        Label(window, text = "Loan Amount").grid(row = 3, 
            column = 1, sticky = W)
        Label(window, text = "Monthly Payment").grid(row = 4, 
            column = 1, sticky = W)
        Label(window, text = "Total Payment").grid(row = 5, 
            column = 1, sticky = W)
        
        self.annualInterestRateVar = StringVar()
        Entry(window, textvariable = self.annualInterestRateVar, 
            justify = RIGHT).grid(row = 1, column = 2)
        self.numberOfYearsVar = StringVar()
        Entry(window, textvariable = self.numberOfYearsVar, 
            justify = RIGHT).grid(row = 2, column = 2)
        self.loanAmountVar = StringVar()
        Entry(window, textvariable = self.loanAmountVar, 
            justify = RIGHT).grid(row = 3, column = 2)
        
        self.monthlyPaymentVar = StringVar()
        lblMonthlyPayment = Label(window, textvariable = 
            self.monthlyPaymentVar).grid(row = 4, column = 2, 
                sticky = E)
        self.totalPaymentVar = StringVar()
        lblTotalPayment = Label(window, textvariable = 
            self.totalPaymentVar).grid(row = 5, 
                column = 2, sticky = E)
        btComputePayment = Button(window, text = "Compute Payment", 
            command = self.computePayment).grid(
                row = 6, column = 2, sticky = E)
        
        window.mainloop() # Create an event loop

    def computePayment(self):
        monthlyPayment = self.getMonthlyPayment(
            float(self.loanAmountVar.get()), 
            float(self.annualInterestRateVar.get()) / 1200, 
            int(self.numberOfYearsVar.get()))
        self.monthlyPaymentVar.set(format(monthlyPayment, '10.2f'))
        totalPayment = float(self.monthlyPaymentVar.get()) * 12 \
            * int(self.numberOfYearsVar.get())
        self.totalPaymentVar.set(format(totalPayment, '10.2f'))
        
    def getMonthlyPayment(self,
            loanAmount, monthlyInterestRate, numberOfYears):
        monthlyPayment = loanAmount * monthlyInterestRate / (1
           - 1 / (1 + monthlyInterestRate) ** (numberOfYears * 12))
        return monthlyPayment;

LoanCalculator()  # Create GUI 
Out[9]:
<__main__.LoanCalculator at 0x1cb3d17ab50>
In [10]:
from tkinter import *

class MenuDemo:
    def __init__(self):
        window = Tk()
        window.title("Menu Demo")
        
        # Create a menu bar
        menubar = Menu(window)
        window.config(menu = menubar) # Display the menu bar
        
        # create a pulldown menu, and add it to the menu bar
        operationMenu = Menu(menubar, tearoff = 0)
        menubar.add_cascade(label = "Operation", menu = operationMenu)
        operationMenu.add_command(label = "Add",  
            command = self.add)
        operationMenu.add_command(label = "Subtract", 
            command = self.subtract)
        operationMenu.add_separator()
        operationMenu.add_command(label = "Multiply", 
            command = self.multiply)
        operationMenu.add_command(label = "Divide", 
            command = self.divide)
        
        # create more pulldown menus
        exitmenu = Menu(menubar, tearoff = 0)
        menubar.add_cascade(label = "Exit", menu = exitmenu)
        exitmenu.add_command(label = "Quit", command = window.quit)
        
        # Add a tool bar frame 
        frame0 = Frame(window) # Create and add a frame to window
        frame0.grid(row = 1, column = 1, sticky = W)
        
        # Create images
        plusImage = PhotoImage(file = "image/plus.gif")
        minusImage = PhotoImage(file = "image/minus.gif")
        timesImage = PhotoImage(file = "image/times.gif")
        divideImage = PhotoImage(file = "image/divide.gif")
        
        Button(frame0, image = plusImage, command = 
            self.add).grid(row = 1, column = 1, sticky = W)
        Button(frame0, image = minusImage,
            command = self.subtract).grid(row = 1, column = 2)
        Button(frame0, image = timesImage,  
            command = self.multiply).grid(row = 1, column = 3)
        Button(frame0, image = divideImage, 
            command = self.divide).grid(row = 1, column = 4)
        
        # Add labels and entries to frame1
        frame1 = Frame(window)
        frame1.grid(row = 2, column = 1, pady = 10)
        Label(frame1, text = "Number 1:").pack(side = LEFT)
        self.v1 = StringVar()
        Entry(frame1, width = 5, textvariable = self.v1, 
              justify = RIGHT).pack(side = LEFT)
        Label(frame1, text = "Number 2:").pack(side = LEFT)
        self.v2 = StringVar()
        Entry(frame1, width = 5, textvariable = self.v2, 
              justify = RIGHT).pack(side = LEFT)
        Label(frame1, text = "Result:").pack(side = LEFT)
        self.v3 = StringVar()
        Entry(frame1, width = 5, textvariable = self.v3, 
              justify = RIGHT).pack(side = LEFT)
        
        # Add buttons to frame2
        frame2 = Frame(window) # Create and add a frame to window
        frame2.grid(row = 3, column = 1, pady = 10, sticky = E)
        Button(frame2, text = "Add", command = self.add).pack(
            side = LEFT)
        Button(frame2, text = "Subtract", 
               command = self.subtract).pack(side = LEFT)
        Button(frame2, text = "Multiply", 
               command = self.multiply).pack(side = LEFT)
        Button(frame2, text = "Divide", 
               command = self.divide).pack(side = LEFT)
               
        mainloop()
        
    def add(self): 
        self.v3.set(eval(self.v1.get()) + eval(self.v2.get()))
    
    def subtract(self):
        self.v3.set(eval(self.v1.get()) - eval(self.v2.get()))
    
    def multiply(self):
        self.v3.set(eval(self.v1.get()) * eval(self.v2.get()))
    
    def divide(self):
        self.v3.set(eval(self.v1.get()) / eval(self.v2.get()))

MenuDemo() # Create GUI 
---------------------------------------------------------------------------
TclError                                  Traceback (most recent call last)
Input In [10], in <cell line: 91>()
     88     def divide(self):
     89         self.v3.set(eval(self.v1.get()) / eval(self.v2.get()))
---> 91 MenuDemo()

Input In [10], in MenuDemo.__init__(self)
     32 frame0.grid(row = 1, column = 1, sticky = W)
     34 # Create images
---> 35 plusImage = PhotoImage(file = "image/plus.gif")
     36 minusImage = PhotoImage(file = "image/minus.gif")
     37 timesImage = PhotoImage(file = "image/times.gif")

File ~\anaconda3\lib\tkinter\__init__.py:4064, in PhotoImage.__init__(self, name, cnf, master, **kw)
   4059 def __init__(self, name=None, cnf={}, master=None, **kw):
   4060     """Create an image with NAME.
   4061 
   4062     Valid resource names: data, format, file, gamma, height, palette,
   4063     width."""
-> 4064     Image.__init__(self, 'photo', name, cnf, master, **kw)

File ~\anaconda3\lib\tkinter\__init__.py:4009, in Image.__init__(self, imgtype, name, cnf, master, **kw)
   4007         v = self._register(v)
   4008     options = options + ('-'+k, v)
-> 4009 self.tk.call(('image', 'create', imgtype, name,) + options)
   4010 self.name = name

TclError: couldn't open "image/plus.gif": no such file or directory
In [11]:
from tkinter import * # Import tkinter
    
class PopupMenuDemo:
    def __init__(self):
        window = Tk() # Create a window
        window.title("Popup Menu Demo") # Set title

        # Create a popup menu
        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 = self.displayOval)
        self.menu.add_command(label = "Draw a rectangle", 
            command = self.displayRect)
        self.menu.add_command(label = "Clear", 
            command = self.clearCanvas)
        
        # Place canvas in window
        self.canvas = Canvas(window, width = 200, 
            height = 100, bg = "white")
        self.canvas.pack()
        
        # Bind popup to canvas
        self.canvas.bind("<Button-3>", self.popup)
        
        window.mainloop() # Create an event loop
        
    # Display a rectangle
    def displayRect(self):
        self.canvas.create_rectangle(10, 10, 190, 90, tags = "rect")
        
    # Display an oval
    def displayOval(self):
        self.canvas.create_oval(10, 10, 190, 90, tags = "oval")
    
    # Display a line
    def displayLine(self):
        self.canvas.create_line(10, 10, 190, 90, tags = "line")
        self.canvas.create_line(10, 90, 190, 10, tags = "line")
    
    # Clear drawings
    def clearCanvas(self):
        self.canvas.delete("rect", "oval", "line")

    def popup(self, event):
        self.menu.post(event.x_root, event.y_root)
    
PopupMenuDemo() # Create GUI
Out[11]:
<__main__.PopupMenuDemo at 0x1cb3daab1f0>
In [12]:
from tkinter import * # Import tkinter

class MouseKeyEventDemo:
    def __init__(self):
        window = Tk() # Create a window
        window.title("Event Demo") # Set a title
        canvas = Canvas(window, bg = "white", width = 200, height = 100)
        canvas.pack()
        
        # Bind with <Button-1> event
        canvas.bind("<Button-1>", self.processMouseEvent)
        
        # Bind with <Key> event
        canvas.bind("<Key>", self.processKeyEvent)
        canvas.focus_set()
        
        window.mainloop() # Create an event loop

    def processMouseEvent(self, event):
        print("clicked at", event.x, event.y)
        print("Position in the screen", event.x_root, event.y_root)
        print("Which button is clicked? ", event.num)
    
    def processKeyEvent(self, event):    
        print("keysym? ", event.keysym)
        print("char? ", event.char)
        print("keycode? ", event.keycode)
    
MouseKeyEventDemo() # Create GUI
clicked at 43 31
Position in the screen 3295 458
Which button is clicked?  1
clicked at 58 34
Position in the screen 3310 461
Which button is clicked?  1
keysym?  a
char?  a
keycode?  65
keysym?  Shift_R
char?  
keycode?  16
keysym?  Shift_R
char?  
keycode?  16
keysym?  Shift_R
char?  
keycode?  16
keysym?  Shift_R
char?  
keycode?  16
keysym?  Shift_R
char?  
keycode?  16
keysym?  Shift_R
char?  
keycode?  16
keysym?  Shift_R
char?  
keycode?  16
keysym?  Shift_R
char?  
keycode?  16
keysym?  Shift_R
char?  
keycode?  16
keysym?  Shift_R
char?  
keycode?  16
keysym?  Shift_R
char?  
keycode?  16
keysym?  Shift_R
char?  
keycode?  16
keysym?  A
char?  A
keycode?  65
keysym?  Shift_R
char?  
keycode?  16
keysym?  Shift_R
char?  
keycode?  16
keysym?  Up
char?  
keycode?  38
keysym?  Insert
char?  
keycode?  45
clicked at 28 29
Position in the screen 3280 456
Which button is clicked?  1
clicked at 23 34
Position in the screen 3085 705
Which button is clicked?  1
clicked at 8 30
Position in the screen 3070 701
Which button is clicked?  1
Out[12]:
<__main__.MouseKeyEventDemo at 0x1cb3bf49370>
In [13]:
from tkinter import * # Import tkinter

window = Tk() # Create a window
window.title("Control Circle Demo") # Set a title

def increaseCircle(event):
    canvas.delete("oval")
    global radius
    if radius < 100:
        radius += 2
    canvas.create_oval(100 - radius, 100 - radius, 
                       100 + radius, 100 + radius, tags = "oval")
    
def decreaseCircle(event):
    canvas.delete("oval")
    global radius
    if radius > 2:
        radius -= 2
    canvas.create_oval(100 - radius, 100 - radius, 
                       100 + radius, 100 + radius, tags = "oval")

canvas = Canvas(window, bg = "white", width = 200, height = 200)
canvas.pack()
radius = 50
canvas.create_oval(100 - radius, 100 - radius, 
                   100 + radius, 100 + radius, tags = "oval")

# Bind canvas with mouse events
canvas.bind("<Button-1>", increaseCircle)
canvas.bind("<Button-3>", decreaseCircle)

window.mainloop() # Create an event loop
In [14]:
from tkinter import * # Import tkinter

class AnimationDemo:
    def __init__(self):
        window = Tk() # Create a window
        window.title("Animation Demo") # Set a title
        
        width = 250 # Width of the canvas
        canvas = Canvas(window, bg = "white", 
            width = 250, height = 50)
        canvas.pack()
        
        x = 0 # Starting x position
        canvas.create_text(x, 30, 
            text = "Message moving?", tags = "text")
        
        dx = 3
        while True:
            canvas.move("text", dx, 0) # Move text dx unit
            canvas.after(100) # Sleep for 100 milliseconds
            canvas.update() # Update canvas
            if x < width:
                x += dx  # Get the current position for string
            else:
                x = 0 # Reset string position to the beginning
                canvas.delete("text") 
                # Redraw text at the beginning
                canvas.create_text(x, 30, text = "Message moving?", 
                    tags = "text")
                
        window.mainloop() # Create an event loop

AnimationDemo() # Create GUI
---------------------------------------------------------------------------
TclError                                  Traceback (most recent call last)
Input In [14], in <cell line: 33>()
     28                 canvas.create_text(x, 30, text = "Message moving?", 
     29                     tags = "text")
     31         window.mainloop() # Create an event loop
---> 33 AnimationDemo()

Input In [14], in AnimationDemo.__init__(self)
     17 dx = 3
     18 while True:
---> 19     canvas.move("text", dx, 0) # Move text dx unit
     20     canvas.after(100) # Sleep for 100 milliseconds
     21     canvas.update() # Update canvas

File ~\anaconda3\lib\tkinter\__init__.py:2920, in Canvas.move(self, *args)
   2918 def move(self, *args):
   2919     """Move an item TAGORID given in ARGS."""
-> 2920     self.tk.call((self._w, 'move') + args)

TclError: invalid command name ".!canvas"
In [15]:
from tkinter import * # Import tkinter

class ControlAnimation:
    def __init__(self):
        window = Tk() # Create a window
        window.title("Control Animation Demo") # Set a title
        
        self.width = 250 # Width of the self.canvas
        self.canvas = Canvas(window, bg = "white", 
            width = self.width, height = 50)
        self.canvas.pack()
        
        frame = Frame(window)
        frame.pack()
        btStop = Button(frame, text = "Stop", command = self.stop)
        btStop.pack(side = LEFT)
        btResume = Button(frame, text = "Resume", 
            command = self.resume)
        btResume.pack(side = LEFT)
        btFaster = Button(frame, text = "Faster", 
            command = self.faster)
        btFaster.pack(side = LEFT)
        btSlower = Button(frame, text = "Slower", 
            command = self.slower)
        btSlower.pack(side = LEFT)
        
        self.x = 0 # Starting x position
        self.sleepTime = 100 # Set a sleep time 
        self.canvas.create_text(self.x, 30, 
            text = "Message moving?", tags = "text")
        
        self.dx = 3
        self.isStopped = False
        self.animate()
        
        window.mainloop() # Create an event loop
        
    def stop(self): # Stop animation
        self.isStopped = True
    
    def resume(self): # Resume animation
        self.isStopped = False   
        self.animate()
    
    def faster(self): # Speed up the animation
        if self.sleepTime > 5:
            self.sleepTime -= 20
               
    def slower(self): # Slow down the animation
        self.sleepTime += 20
                                
    def animate(self): # Move the message
        while not self.isStopped:
            self.canvas.move("text", self.dx, 0) # Move text 
            self.canvas.after(self.sleepTime) # Sleep 
            self.canvas.update() # Update self.canvas
            if self.x < self.width:
                self.x += self.dx  # Set new position 
            else:
                self.x = 0 # Reset string position to the beginning
                self.canvas.delete("text") 
                # Redraw text at the beginning
                self.canvas.create_text(self.x, 30, 
                    text = "Message moving?", tags = "text")    
                                       
ControlAnimation() # Create GUI
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\sakyo\anaconda3\lib\tkinter\__init__.py", line 1892, in __call__
    return self.func(*args)
  File "C:\Users\sakyo\AppData\Local\Temp\ipykernel_6800\330264902.py", line 43, in resume
    self.animate()
  File "C:\Users\sakyo\AppData\Local\Temp\ipykernel_6800\330264902.py", line 54, in animate
    self.canvas.move("text", self.dx, 0) # Move text
  File "C:\Users\sakyo\anaconda3\lib\tkinter\__init__.py", line 2920, in move
    self.tk.call((self._w, 'move') + args)
_tkinter.TclError: invalid command name ".!canvas"
Out[15]:
<__main__.ControlAnimation at 0x1cb3dac3c40>
In [16]:
from tkinter import * # Import tkinter
    
class ScrollText:
    def __init__(self):
        window = Tk() # Create a window
        window.title("Scroll Text Demo") # Set title
        
        frame1 = Frame(window)
        frame1.pack()
        scrollbar = Scrollbar(frame1)
        scrollbar.pack(side = RIGHT, fill = Y)
        text = Text(frame1, width = 40, height = 10, wrap = WORD, 
                    yscrollcommand = scrollbar.set)
        text.pack()
        scrollbar.config(command = text.yview)
        
        window.mainloop() # Create an event loop

ScrollText() # Create GUI
Out[16]:
<__main__.ScrollText at 0x1cb3e2e2220>
In [17]:
import tkinter.messagebox
import tkinter.simpledialog
import tkinter.colorchooser

tkinter.messagebox.showinfo("showinfo", "This is an info msg")

tkinter.messagebox.showwarning("showwarning", "This is a warning")

tkinter.messagebox.showerror("showerror", "This is an error")

isYes = tkinter.messagebox.askyesno("ashyesno", "Continue?")
print(isYes)

isOK = tkinter.messagebox.askokcancel("ashokcancle", "OK?")
print(isOK)

isYesNoCancel = tkinter.messagebox.askyesnocancel(
    "askyesnocancel", "Yes, No, Cancel?") 
print(isYesNoCancel)

name = tkinter.simpledialog.askstring(
    "askstring", "Enter your name")
print(name)

age = tkinter.simpledialog.askinteger(
    "askinteger", "Enter your age")
print(age)

weight = tkinter.simpledialog.askfloat(
    "askfloat", "Enter your weight")
print(weight)
True
False
True
selim
33
5.5
In [ ]: