Minggu, 05 Oktober 2025

PYTHON - PYGAME

 





# Examples of the math.sin() and math.cos() trig functions

# Al Sweigart al@inventwithpython.com


# You can learn more about Pygame with the

# free book "Making Games with Python & Pygame"

#

# http://inventwithpython.com/pygame

#


import sys, pygame, math

from pygame.locals import *


# set up a bunch of constants

BLUE       = (  0,   0, 255)

WHITE      = (255, 255, 255)

DARKRED    = (128,   0,   0)

DARKBLUE   = (  0,   0, 128)

RED        = (255,   0,   0)

GREEN      = (  0, 255,   0)

DARKGREEN  = (  0, 128,   0)

YELLOW     = (255, 255,   0)

DARKYELLOW = (128, 128,   0)

BLACK      = (  0,   0,   0)


BGCOLOR = WHITE


WINDOWWIDTH = 640 # width of the program's window, in pixels

WINDOWHEIGHT = 480 # height in pixels

WIN_CENTERX = int(WINDOWWIDTH / 2) # the midpoint for the width of the window

WIN_CENTERY = int(WINDOWHEIGHT / 2) # the midpoint for the height of the window


FPS = 160 # frames per second to run at


AMPLITUDE = 100 # how many pixels tall the waves with rise/fall.


# standard pygame setup code

pygame.init()

FPSCLOCK = pygame.time.Clock()

DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))

pygame.display.set_caption('Trig Waves')

fontObj = pygame.font.Font('freesansbold.ttf', 16)


# variables that track visibility modes

showSine = True

showCosine = True

showHighAmpSine = True

showHighFreqSine = True

pause = False


xPos = 0

step = 0 # the current input f

posRecord = {'sin': [], 'cos': [], 'hiampsin': [], 'hifreqsin': []} # keeps track of the ball positions for drawing the waves


# making text Surface and Rect objects for various labels

sinLabelSurf         = fontObj.render('sine', True, RED, BGCOLOR)

cosLabelSurf         = fontObj.render('cosine', True, BLUE, BGCOLOR)

highAmpSinLabelSurf  = fontObj.render('hi amp sin', True, GREEN, BGCOLOR)

highFreqSinLabelSurf = fontObj.render('hi freq sin', True, YELLOW, BGCOLOR)


sinLabelRect         = sinLabelSurf.get_rect()

cosLabelRect         = cosLabelSurf.get_rect()

highAmpSinLabelRect  = highAmpSinLabelSurf.get_rect()

highFreqSinLabelRect = highFreqSinLabelSurf.get_rect()


instructionsSurf = fontObj.render('Press Q, W, E, R to toggle waves. P to pause.', True, BLACK, BGCOLOR)

instructionsRect = instructionsSurf.get_rect()

instructionsRect.left = 10

instructionsRect.bottom = WINDOWHEIGHT - 10


# main application loop

while True:

    # event handling loop for quit events

    for event in pygame.event.get():

        if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):

            pygame.quit()

            sys.exit()


        # check for key presses that toggle pausing and wave visibility

        if event.type == KEYUP:

            if event.key == K_q:

                showSine = not showSine

            elif event.key == K_w:

                showCosine = not showCosine

            elif event.key == K_e:

                showHighAmpSine = not showHighAmpSine

            elif event.key == K_r:

                showHighFreqSine = not showHighFreqSine

            elif event.key == K_p:

                pause = not pause


    # fill the screen to draw from a blank state

    DISPLAYSURF.fill(BGCOLOR)


    # draw instructions

    DISPLAYSURF.blit(instructionsSurf, instructionsRect)


    # draw the horizontal middle line and the amplitude lines

    pygame.draw.line(DISPLAYSURF, BLACK, (0, WIN_CENTERY), (WINDOWWIDTH, WIN_CENTERY))

    pygame.draw.line(DISPLAYSURF, BLACK, (0, WIN_CENTERY + AMPLITUDE), (WINDOWWIDTH, WIN_CENTERY + AMPLITUDE))

    pygame.draw.line(DISPLAYSURF, BLACK, (0, WIN_CENTERY - AMPLITUDE), (WINDOWWIDTH, WIN_CENTERY - AMPLITUDE))



    # sine wave

    yPos = -1 * math.sin(step) * AMPLITUDE

    posRecord['sin'].append((int(xPos), int(yPos) + WIN_CENTERY))

    if showSine:

        # draw the sine ball and label

        pygame.draw.circle(DISPLAYSURF, RED, (int(xPos), int(yPos) + WIN_CENTERY), 10)

        sinLabelRect.center = (int(xPos), int(yPos) + WIN_CENTERY + 20)

        DISPLAYSURF.blit(sinLabelSurf, sinLabelRect)



    # cosine wave

    yPos = -1 * math.cos(step) * AMPLITUDE

    posRecord['cos'].append((int(xPos), int(yPos) + WIN_CENTERY))

    if showCosine:

        # draw the cosine ball and label

        pygame.draw.circle(DISPLAYSURF, BLUE, (int(xPos), int(yPos) + WIN_CENTERY), 10)

        cosLabelRect.center = (int(xPos), int(yPos) + WIN_CENTERY + 20)

        DISPLAYSURF.blit(cosLabelSurf, cosLabelRect)



    # high amplitude sine wave

    yPos = -1 * math.sin(step) * (AMPLITUDE + 100) # Note the "+ 100" to the amplitude!

    posRecord['hiampsin'].append((int(xPos), int(yPos) + WIN_CENTERY))

    if showHighAmpSine:

        # draw the high amplitude sine ball and label

        pygame.draw.circle(DISPLAYSURF, GREEN, (int(xPos), int(yPos) + WIN_CENTERY), 10)

        highAmpSinLabelRect.center = (int(xPos), int(yPos) + WIN_CENTERY + 20)

        DISPLAYSURF.blit(highAmpSinLabelSurf, highAmpSinLabelRect)



    # high frequency sine wave

    yPos = -1 * math.sin(step * 4) * AMPLITUDE # Note the "* 4" to the frequency

    posRecord['hifreqsin'].append((int(xPos), int(yPos) + WIN_CENTERY))

    if showHighFreqSine:

        # draw the high frequency sine ball and label

        pygame.draw.circle(DISPLAYSURF, YELLOW, (int(xPos), int(yPos) + WIN_CENTERY), 10)

        highFreqSinLabelRect.center = (int(xPos), int(yPos) + WIN_CENTERY + 20)

        DISPLAYSURF.blit(highFreqSinLabelSurf, highFreqSinLabelRect)




    # draw the waves from the previously recorded ball positions

    if showSine:

        for x, y in posRecord['sin']:

            pygame.draw.circle(DISPLAYSURF, DARKRED, (x, y), 4)

    if showCosine:

        for x, y in posRecord['cos']:

            pygame.draw.circle(DISPLAYSURF, DARKBLUE, (x, y), 4)

    if showHighAmpSine:

        for x, y in posRecord['hiampsin']:

            pygame.draw.circle(DISPLAYSURF, DARKGREEN, (x, y), 4)

    if showHighFreqSine:

        for x, y in posRecord['hifreqsin']:

            pygame.draw.circle(DISPLAYSURF, DARKYELLOW, (x, y), 4)


    # draw the border

    pygame.draw.rect(DISPLAYSURF, BLACK, (0, 0, WINDOWWIDTH, WINDOWHEIGHT), 1)


    pygame.display.update()

    FPSCLOCK.tick(FPS)


    if not pause:

        xPos += 0.5

        if xPos > WINDOWWIDTH:

            xPos = 0

            posRecord = {'sin': [], 'cos': [], 'hiampsin': [], 'hifreqsin': []}

            step = 0

        else:

            step += 0.008

            step %= 2 * math.pi


PYTHON - PYGAME - CLOCK

 





# Examples of the math.sin() and math.cos() trig functions in making a clock

# Al Sweigart al@inventwithpython.com


# You can learn more about Pygame with the

# free book "Making Games with Python & Pygame"

#

# http://inventwithpython.com/pygame

#


import sys, pygame, time, math

from pygame.locals import *


# set up a bunch of constants

BRIGHTBLUE = (  0,  50, 255)

WHITE      = (255, 255, 255)

DARKRED    = (128,   0,   0)

RED        = (255,   0,   0)

YELLOW     = (255, 255,   0)

BLACK      = (  0,   0,   0)


HOURHANDCOLOR = DARKRED

MINUTEHANDCOLOR = RED

SECONDHANDCOLOR = YELLOW

NUMBERBOXCOLOR = BRIGHTBLUE

BGCOLOR = WHITE


WINDOWWIDTH = 640 # width of the program's window, in pixels

WINDOWHEIGHT = 480 # height in pixels

WIN_CENTERX = int(WINDOWWIDTH / 2)

WIN_CENTERY = int(WINDOWHEIGHT / 2)



CLOCKNUMSIZE = 40 # size of the clock number's boxes

CLOCKSIZE = 200 # general size of the clock



# This function retrieves the x, y coordinates based on a "tick" mark, which ranges between 0 and 60

# A "tick" of 0 is at the top of the circle, 30 is at the bottom, 45 is at the "9 o'clock" position, etc.

# The "stretch" is how far from the origin the x, y return values will be

# "originx" and "originy" will be where the center of the circle is (almost always the center of the window)

def getTickPosition(tick, stretch=1.0, originx=WIN_CENTERX, originy=WIN_CENTERY):

    # uncomment to have a "rotating clock" feature.

    # This works by pushing the "tick" amount forward

    #tick += (time.time() % 15) * 4


    # The cos() and sin()

    tick -= 15


    # ensure that tick is between 0 and 60

    tick = tick % 60


    tick = 60 - tick


    # the argument to sin() or cos() needs to range between 0 and 2 * math.pi

    # Since tick is always between 0 and 60, (tick / 60.0) will always be between 0.0 and 1.0

    # The (tick / 60.0) lets us break up the range between 0 and 2 * math.pi into 60 increments.

    x =      math.cos(2 * math.pi * (tick / 60.0))

    y = -1 * math.sin(2 * math.pi * (tick / 60.0)) # "-1 *" because in Pygame, the y coordinates increase going down (the opposite of how they normally go in mathematics)


    # sin() and cos() return a number between -1.0 and 1.0, so multiply to stretch it out.

    x *= stretch

    y *= stretch


    # Then do the translation (i.e. sliding) of the x and y points.

    # NOTE: Always do the translation addition AFTER doing the stretch.

    x += originx

    y += originy


    return x, y



# these next 2 lines are used by the "pulsing clock" feature (see below)

originalClockSize = CLOCKSIZE

PULSESIZE = 20


# standard pygame setup code

pygame.init()

DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))

pygame.display.set_caption('Trig Clock')

fontObj = pygame.font.Font('freesansbold.ttf', 26)


# render the Surface objects that have the clock numbers written on them

clockNumSurfs = [fontObj.render('%s' % (i), True, BGCOLOR, NUMBERBOXCOLOR)

                 for i in [12] + list(range(1, 12))] # Put 12 at the front of the list since clocks start at 12, not 1.



while True: # main application loop

    # event handling loop for quit events

    for event in pygame.event.get():

        if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):

            pygame.quit()

            sys.exit()


    # fill the screen to draw from a blank state

    DISPLAYSURF.fill(BGCOLOR)


    # draw the numbers and number boxes of the clock

    for i in range(12):

        # set up the Rect objects for the numbers and the number boxes

        clockNumRect = clockNumSurfs[i].get_rect()

        clockNumRect.center = getTickPosition(i * 5, CLOCKSIZE)


        clockNumBoxRect = clockNumSurfs[i].get_rect()

        clockNumBoxRect.size = (CLOCKNUMSIZE, CLOCKNUMSIZE)

        clockNumBoxRect.center = getTickPosition(i * 5, CLOCKSIZE)


        # draw the numbers and the number boxes

        pygame.draw.rect(DISPLAYSURF, NUMBERBOXCOLOR, clockNumBoxRect)

        DISPLAYSURF.blit(clockNumSurfs[i], clockNumRect)


    # get the current time

    now = time.localtime()

    now_hour = now[3] % 12 # now[3] ranges from 0 to 23, so we mod 12.

    now_minute = now[4]

    now_second = now[5] + (time.time() % 1) # add the fraction of a second we get from time.time() to make a smooth-moving seconds hand


    # Uncomment this if you don't want the second hand to move smoothly:

    #now_second = now[5]


    # draw the hour hand

    x, y = getTickPosition(now_hour * 5 + (now_minute * 5 / 60.0), CLOCKSIZE * 0.6)

    pygame.draw.line(DISPLAYSURF, HOURHANDCOLOR, (WIN_CENTERX, WIN_CENTERY), (x, y), 8)


    # draw the minute hand

    x, y = getTickPosition(now_minute + (now_second / 60.0), CLOCKSIZE * 0.8)

    pygame.draw.line(DISPLAYSURF, MINUTEHANDCOLOR, (WIN_CENTERX, WIN_CENTERY), (x, y), 6)


    # draw the second hand

    x, y = getTickPosition(now_second, CLOCKSIZE * 0.8)

    pygame.draw.line(DISPLAYSURF, SECONDHANDCOLOR, (WIN_CENTERX, WIN_CENTERY), (x, y), 2)


    # draw the second hand's part that sticks out behind

    x, y = getTickPosition(now_second, CLOCKSIZE * -0.2) # negative stretch makes it go in the opposite direction

    pygame.draw.line(DISPLAYSURF, SECONDHANDCOLOR, (WIN_CENTERX, WIN_CENTERY), (x, y), 2)


    # draw border

    pygame.draw.rect(DISPLAYSURF, BLACK, (0, 0, WINDOWWIDTH, WINDOWHEIGHT), 1)


    pygame.display.update()


    # Uncomment this if you want the "pulsing clock" feature:

    #CLOCKSIZE = originalClockSize + math.sin(2 * math.pi * (time.time() % 1)) * PULSESIZE


PYTHON - PYGAME 2

 





# Examples of the math.sin() and math.cos() trig functions

# Al Sweigart al@inventwithpython.com


# You can learn more about Pygame with the

# free book "Making Games with Python & Pygame"

#

# http://inventwithpython.com/pygame

#


import sys, pygame, math

from pygame.locals import *


# set up a bunch of constants

WHITE    = (255, 255, 255)

BLACK    = (  0,   0,   0)

BROWN    = (139,  69,  19)

DARKGRAY = (128, 128, 128)


BGCOLOR = WHITE


WINDOWWIDTH = 640 # width of the program's window, in pixels

WINDOWHEIGHT = 480 # height in pixels


FPS = 30



# standard pygame setup code

pygame.init()

FPSCLOCK = pygame.time.Clock()

DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))

pygame.display.set_caption('Trig Pointer')


# create the base cannon image

cannonSurf = pygame.Surface((100, 100))

cannonSurf.fill(BGCOLOR)

pygame.draw.circle(cannonSurf, DARKGRAY, (20, 50), 20) # left end

pygame.draw.circle(cannonSurf, DARKGRAY, (80, 50), 20) # right end

pygame.draw.rect(cannonSurf, DARKGRAY, (20, 30, 60, 40)) # body

pygame.draw.circle(cannonSurf, BLACK, (80, 50), 15) # hole

pygame.draw.circle(cannonSurf, BLACK, (80, 50), 20, 1) # right end outline

pygame.draw.circle(cannonSurf, BROWN, (30, 70), 20) # wheel

pygame.draw.circle(cannonSurf, BLACK, (30, 70), 20, 1) # wheel outline



def getAngle(x1, y1, x2, y2):

    # Return value is 0 for right, 90 for up, 180 for left, and 270 for down (and all values between 0 and 360)

    rise = y1 - y2

    run = x1 - x2

    angle = math.atan2(run, rise) # get the angle in radians

    angle = angle * (180 / math.pi) # convert to degrees

    angle = (angle + 90) % 360 # adjust for a right-facing sprite

    return angle



# main application loop

while True:

    # event handling loop for quit events

    for event in pygame.event.get():

        if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):

            pygame.quit()

            sys.exit()


    # fill the screen to draw from a blank state

    DISPLAYSURF.fill(BGCOLOR)


    # draw the cannons pointed at the mouse cursor

    mousex, mousey = pygame.mouse.get_pos()

    for cannonx, cannony in ((200, 150), (50, 300), (50, 50), (200, 400)):


        degrees = getAngle(cannonx, cannony, mousex, mousey)


        # rotate a copy of the cannon image and draw it

        rotatedSurf = pygame.transform.rotate(cannonSurf, degrees)

        rotatedRect = rotatedSurf.get_rect()

        rotatedRect.center = (cannonx, cannony)

        DISPLAYSURF.blit(rotatedSurf, rotatedRect)


    # draw the cross hairs over the mouse

    pygame.draw.line(DISPLAYSURF, BLACK, (mousex - 10, mousey), (mousex + 10, mousey))

    pygame.draw.line(DISPLAYSURF, BLACK, (mousex, mousey - 10), (mousex, mousey + 10))


    # draw the border

    pygame.draw.rect(DISPLAYSURF, BLACK, (0, 0, WINDOWWIDTH, WINDOWHEIGHT), 1)


    pygame.display.update()

    FPSCLOCK.tick(FPS)

PYTHON - PYGAME

 






# Examples of the math.sin() and math.cos() trig functions

# Al Sweigart al@inventwithpython.com


# You can learn more about Pygame with the

# free book "Making Games with Python & Pygame"

#

# http://inventwithpython.com/pygame

#


import sys, pygame, math

from pygame.locals import *


# set up a bunch of constants

BRIGHTBLUE = (  0,  50, 255)

RED        = (255,   0,   0)

WHITE      = (255, 255, 255)

BLACK      = (  0,   0,   0)


BGCOLOR = WHITE


WINDOWWIDTH = 640 # width of the program's window, in pixels

WINDOWHEIGHT = 480 # height in pixels

WIN_CENTERX = int(WINDOWWIDTH / 2)

WIN_CENTERY = int(WINDOWHEIGHT / 2)


FPS = 60


PERIOD_INCREMENTS = 500.0

AMPLITUDE = 100


# standard pygame setup code

pygame.init()

FPSCLOCK = pygame.time.Clock()

DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))

pygame.display.set_caption('Trig Bounce')


step = 0


# main application loop

while True:

    # event handling loop for quit events

    for event in pygame.event.get():

        if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):

            pygame.quit()

            sys.exit()


    # fill the screen to draw from a blank state

    DISPLAYSURF.fill(BGCOLOR)


    # draw waving ball

    yPos = -1 * math.sin(step) * AMPLITUDE

    pygame.draw.circle(DISPLAYSURF, BRIGHTBLUE, (int(WINDOWWIDTH * 0.333), int(yPos) + WIN_CENTERY), 40)


    # draw waving ball

    yPos = -1 * abs(math.sin(step)) * AMPLITUDE

    pygame.draw.circle(DISPLAYSURF, RED, (int(WINDOWWIDTH * 0.666), int(yPos) + WIN_CENTERY), 40)



    # draw the border

    pygame.draw.rect(DISPLAYSURF, BLACK, (0, 0, WINDOWWIDTH, WINDOWHEIGHT), 1)


    pygame.display.update()

    FPSCLOCK.tick(FPS)


    step += 0.02

    step %= 2 * math.pi

PYTHON - TKINTER - MESSAGE

 





import tkinter


def main():

    main_window = tkinter.Tk()


    main_window.title('Message')

    str_quote = "Real friends are hard to find, difficult to leave and impossible to forget."

    msg = tkinter.Message(main_window, text = str_quote,

                 padx=20, pady=20, bd=5)

    msg.config(bg='green', fg='white', font=('verdana', 30))

    msg.pack()

    main_window.mainloop()


main()

Sabtu, 04 Oktober 2025

PYTHON - TKINTER - OPTIONMENU 5

 




import tkinter


OPTIONS = [

"Jan",

"Feb",

"Mar"

] #etc


master = tkinter.Tk()


variable = tkinter.StringVar(master)

variable.set(OPTIONS[0]) # default value


w = tkinter.OptionMenu(master, variable, *OPTIONS)

w.pack()


def ok():

    print ("value is:" + variable.get())


button = tkinter.Button(master, text="OK", command=ok)

button.pack()


master.mainloop()

PYTHON - TKINTER - OPTIONMENU 4

 





import tkinter


OPTIONS = [

"Jan",

"Feb",

"Mar"

] #etc


master = tkinter.Tk()


variable = tkinter.StringVar(master)

variable.set(OPTIONS[0]) # default value


w = tkinter.OptionMenu(master, variable, *OPTIONS)

w.place(x=10, y=10)

w.pack()


master.mainloop()

PYTHON - TKINTER - OPTIONMENU 3

 




import tkinter


master = tkinter.Tk()


variable = tkinter.StringVar(master)

variable.set("one") # default value


w = tkinter.OptionMenu(master, variable, "one", "two", "three")

w.pack()


master.mainloop()

PYTHON - TKINTER - OPTIONMENU 2

 




import tkinter


def func(value):

    print(value)


root = tkinter.Tk()


var = tkinter.StringVar()

DropDownMenu=tkinter.OptionMenu(root, var, "1", "2", "3", command=func)

DropDownMenu.place(x=10, y=10)


root.mainloop()

PYTHON - TKINTER - OptionMenu

 




import tkinter


### メイン画面作成

main = tkinter.Tk()



Options=["1", "2", "3"]

var = tkinter.StringVar()

menu = tkinter.OptionMenu(main, var, *Options) 

menu.place(x=10, y=10)


main.mainloop()

PYTHON - TKINTER - MENU

 




### インポート

import tkinter


### メイン画面作成

main = tkinter.Tk()

main.title('SMA INFORMATIKA CIAMIS')


### 画面サイズ設定

main.geometry("500x500")


### メニューバー作成

menubar = tkinter.Menu(master=main)


### ファイルメニュー作成

filemenu = tkinter.Menu(master=menubar, tearoff=0)

filemenu.add_command(label="YPBN")

filemenu.add_command(label="Kepala Sekolah")

###filemenu.add_separator()

filemenu.add_command(label="Tata Usaha", command=main.quit)


### 編集メニュー作成

editmenu = tkinter.Menu(master=menubar, tearoff=0)

editmenu.add_command(label="OSIS")

editmenu.add_command(label="Pramuka")

editmenu.add_command(label="PMR")

editmenu.add_command(label="IRMA")

editmenu.add_command(label="Paskibra")

editmenu.add_command(label="English Club")

editmenu.add_command(label="Paduan Suara")

editmenu.add_command(label="Japanese Club")

editmenu.add_command(label="Marawis")

editmenu.add_command(label="Jurnalis & Fotografi")

editmenu.add_command(label="Polisi Pelajar")

editmenu.add_command(label="Format Biker")

editmenu.add_command(label="Puseur Galuh")

editmenu.add_command(label="Pecinta Alam")

editmenu.add_command(label="Bocah Lab Desain & Film")


editmenu.add_separator()


### 設定メニュー作成

setmenu = tkinter.Menu(master=menubar, tearoff=0)

setmenu.add_checkbutton(label="Basket Ball")

setmenu.add_checkbutton(label="Volley Ball")

setmenu.add_checkbutton(label="Sepak Bola")

setmenu.add_checkbutton(label="Futsal")

setmenu.add_radiobutton(label="Petanque")


pp = tkinter.Menu(master=menubar, tearoff=0)

pp.add_command(label="Multimedia")

pp.add_command(label="Komputer Akuntansi")

pp.add_command(label="Administrasi Perkantoran")

pp.add_command(label="Teknik Komputer Jaringan")

pp.add_command(label="Rekayasa Perangkat Lunak")

pp.add_command(label="Praktek Kerja Lapangan-PAKK")

pp.add_command(label="Bahasa Jepang dan Arab")


### 各メニューを設定

menubar.add_cascade(label="File", menu=filemenu)

menubar.add_cascade(label="Program Plus", menu=pp)

menubar.add_cascade(label="Ekstrakurikuler", menu=editmenu)

editmenu.add_cascade(label="Olahraga", menu=setmenu)


### メニューバー配置

main.config(menu=menubar)


### イベントループ

main.mainloop()


PYTHON - TKINTER - TABEL PERKALIAN

 


import tkinter





def show_table():

num = int(entry.get())

str1=' Table of ' + str(num) + '\n-----------------\n'

for i in range(1,11):

str1 = str1 + " " + str(num) + " x " + str(i) + " = " + str(num*i) + "\n"


output_label.configure(text = str1)

main_window = tkinter.Tk()

main_window.title("Perfect Python tkinter Tutorials : www.EasyCodeBook.com")

message_label =tkinter.Label(text= ' Enter a number to \ndisplay its Table ' ,

font=( ' Verdana ' , 12))

output_label = tkinter.Label(font=( ' Verdana ' , 12))

entry = tkinter.Entry(font=( ' Verdana ' , 12), width=6)

calc_button = tkinter.Button(text= ' Show Multiplication Table ' , font=( ' Verdana ', 12), 

command=show_table)

message_label.grid(row=0, column=0,padx=10, pady=10)

entry.grid(row=0, column=1,padx=10, pady=10, ipady=10)

calc_button.grid(row=0, column=2,padx=10, pady=10)

output_label.grid(row=1, column=0, columnspan=3,padx=10, pady=10)

main_window.mainloop()

PYTHON - MATPLOTLIB - NUMPY - ANIMATION 3

 





import matplotlib.pyplot as plt

from matplotlib.animation import FuncAnimation

import numpy as np


fig, ax = plt.subplots()

xdata, ydata = [], []

ln, = plt.plot([], [], 'ro')


def init():

    ax.set_xlim(0, 2*np.pi)

    ax.set_ylim(-1, 1)

    return ln,


def update(frame):

    xdata.append(frame)

    ydata.append(np.sin(frame))

    ln.set_data(xdata, ydata)

    return ln,


ani = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128),

                    init_func=init, blit=True)

plt.show()

PYTHON - KIVY 2

 




# Widget animation in kivy



# import kivy module 

import kivy 

  

# this restricts the kivy version i.e 

# below this kivy version you cannot 

# use the app or software 

kivy.require("1.9.1") 

  

# base Class of your App inherits from the App class. 

# app:always refers to the instance of your application 

from kivy.app import App 


# To work with Animation you must have to import it

from kivy.animation import Animation


# The Button is a Label with associated

# actions that are triggered when the button

# is pressed (or released after a click/touch). 

from kivy.uix.button import Button


# Create the App class

class TestApp(App):


   # Defining the function in which animations are added

   

    def animate(self, instance):

        # create an animation object. This object could be stored

        # and reused each call or reused across different widgets.

        # += is a sequential step, while &= is in parallel

        animation = Animation(pos =(100, 100), t ='out_bounce')

        animation += Animation(pos =(200, 100), t ='out_bounce')

        animation += Animation(size =(500, 500))

        animation += Animation(size =(100, 50))


        # apply the animation on the button, passed in the "instance" argument

        # Notice that default 'click' animation (changing the button

        # color while the mouse is down) is unchanged.

        animation.start(instance)


    def build(self):

        # create a button, and  attach animate() 

        # method as a on_press handler

        button = Button(size_hint =(None, None), text ='plop',

                        on_press = self.animate)

        return button


# run the App

if __name__ == '__main__':

    TestApp().run()

PYTHON - KIVY

 



import kivy

from kivy.app import App

from kivy.uix.button import Button

from kivy.animation import Animation


class TestApp(App):

    def build(self):

        btn = Button(text='Animate Me!', size_hint=(None, None), size=(150, 50))

        btn.bind(on_release=self.animate_button)

        return btn


    def animate_button(self, instance):

        animation = Animation(x=200, y=300, duration=1) + \

                    Animation(size=(200, 100), duration=0.5)

        animation.start(instance)


if __name__ == '__main__':

    TestApp().run()

PYTHON - MATPLOTLIB

 




from matplotlib import pyplot as plt

plt.bar([0.25,1.25,2.25,3.25,4.25],[50000,40000,70000,80000,200000],label="MAC",color='r',width=.4)

plt.bar([0.75,1.75,2.75,3.75,4.75],[80000,20000,20000,50000,60000],label="Dominos",color='b',width=.4)

plt.legend(loc='upper right')

plt.xlabel('Months')

plt.ylabel('Sales Amount')

plt.title('Information')

plt.show()

PYTHON - NUMPY - MATPLOTLIB - SCIPY - ANIMATION 2

 





import numpy as np

from scipy.spatial.distance import pdist, squareform


import matplotlib.pyplot as plt

import scipy.integrate as integrate

import matplotlib.animation as animation


class ParticleBox:

    """Orbits class

    

    init_state is an [N x 4] array, where N is the number of particles:

       [[x1, y1, vx1, vy1],

        [x2, y2, vx2, vy2],

        ...               ]


    bounds is the size of the box: [xmin, xmax, ymin, ymax]

    """

    def __init__(self,

                 init_state = [[1, 0, 0, -1],

                               [-0.5, 0.5, 0.5, 0.5],

                               [-0.5, -0.5, -0.5, 0.5]],

                 bounds = [-2, 2, -2, 2],

                 size = 0.04,

                 M = 0.05,

                 G = 9.8):

        self.init_state = np.asarray(init_state, dtype=float)

        self.M = M * np.ones(self.init_state.shape[0])

        self.size = size

        self.state = self.init_state.copy()

        self.time_elapsed = 0

        self.bounds = bounds

        self.G = G


    def step(self, dt):

        """step once by dt seconds"""

        self.time_elapsed += dt

        

        # update positions

        self.state[:, :2] += dt * self.state[:, 2:]


        # find pairs of particles undergoing a collision

        D = squareform(pdist(self.state[:, :2]))

        ind1, ind2 = np.where(D < 2 * self.size)

        unique = (ind1 < ind2)

        ind1 = ind1[unique]

        ind2 = ind2[unique]


        # update velocities of colliding pairs

        for i1, i2 in zip(ind1, ind2):

            # mass

            m1 = self.M[i1]

            m2 = self.M[i2]


            # location vector

            r1 = self.state[i1, :2]

            r2 = self.state[i2, :2]


            # velocity vector

            v1 = self.state[i1, 2:]

            v2 = self.state[i2, 2:]


            # relative location & velocity vectors

            r_rel = r1 - r2

            v_rel = v1 - v2


            # momentum vector of the center of mass

            v_cm = (m1 * v1 + m2 * v2) / (m1 + m2)


            # collisions of spheres reflect v_rel over r_rel

            rr_rel = np.dot(r_rel, r_rel)

            vr_rel = np.dot(v_rel, r_rel)

            v_rel = 2 * r_rel * vr_rel / rr_rel - v_rel


            # assign new velocities

            self.state[i1, 2:] = v_cm + v_rel * m2 / (m1 + m2)

            self.state[i2, 2:] = v_cm - v_rel * m1 / (m1 + m2) 


        # check for crossing boundary

        crossed_x1 = (self.state[:, 0] < self.bounds[0] + self.size)

        crossed_x2 = (self.state[:, 0] > self.bounds[1] - self.size)

        crossed_y1 = (self.state[:, 1] < self.bounds[2] + self.size)

        crossed_y2 = (self.state[:, 1] > self.bounds[3] - self.size)


        self.state[crossed_x1, 0] = self.bounds[0] + self.size

        self.state[crossed_x2, 0] = self.bounds[1] - self.size


        self.state[crossed_y1, 1] = self.bounds[2] + self.size

        self.state[crossed_y2, 1] = self.bounds[3] - self.size


        self.state[crossed_x1 | crossed_x2, 2] *= -1

        self.state[crossed_y1 | crossed_y2, 3] *= -1


        # add gravity

        self.state[:, 3] -= self.M * self.G * dt



#------------------------------------------------------------

# set up initial state

np.random.seed(0)

init_state = -0.5 + np.random.random((50, 4))

init_state[:, :2] *= 3.9


box = ParticleBox(init_state, size=0.04)

dt = 1. / 30 # 30fps



#------------------------------------------------------------

# set up figure and animation

fig = plt.figure()

fig.subplots_adjust(left=0, right=1, bottom=0, top=1)

ax = fig.add_subplot(111, aspect='equal', autoscale_on=False,

                     xlim=(-3.2, 3.2), ylim=(-2.4, 2.4))


# particles holds the locations of the particles

particles, = ax.plot([], [], 'bo', ms=6)


# rect is the box edge

rect = plt.Rectangle(box.bounds[::2],

                     box.bounds[1] - box.bounds[0],

                     box.bounds[3] - box.bounds[2],

                     ec='none', lw=2, fc='none')

ax.add_patch(rect)


def init():

    """initialize animation"""

    global box, rect

    particles.set_data([], [])

    rect.set_edgecolor('none')

    return particles, rect


def animate(i):

    """perform animation step"""

    global box, rect, dt, ax, fig

    box.step(dt)


    ms = int(fig.dpi * 2 * box.size * fig.get_figwidth()

             / np.diff(ax.get_xbound())[0])

    

    # update pieces of the animation

    rect.set_edgecolor('k')

    particles.set_data(box.state[:, 0], box.state[:, 1])

    particles.set_markersize(ms)

    return particles, rect


ani = animation.FuncAnimation(fig, animate, frames=600,

                              interval=10, blit=True, init_func=init)



# save the animation as an mp4.  This requires ffmpeg or mencoder to be

# installed.  The extra_args ensure that the x264 codec is used, so that

# the video can be embedded in html5.  You may need to adjust this for

# your system: for more information, see

# http://matplotlib.sourceforge.net/api/animation_api.html

#ani.save('particle_box.mp4', fps=30, extra_args=['-vcodec', 'libx264'])


plt.show()

PYTHON - NUMPY - MATPLOTLIB - SCIPY - ANIMATION

 




from numpy import sin, cos

import numpy as np

import matplotlib.pyplot as plt

import scipy.integrate as integrate

import matplotlib.animation as animation


class DoublePendulum:

    """Double Pendulum Class


    init_state is [theta1, omega1, theta2, omega2] in degrees,

    where theta1, omega1 is the angular position and velocity of the first

    pendulum arm, and theta2, omega2 is that of the second pendulum arm

    """

    def __init__(self,

                 init_state = [120, 0, -20, 0],

                 L1=1.0,  # length of pendulum 1 in m

                 L2=1.0,  # length of pendulum 2 in m

                 M1=1.0,  # mass of pendulum 1 in kg

                 M2=1.0,  # mass of pendulum 2 in kg

                 G=9.8,  # acceleration due to gravity, in m/s^2

                 origin=(0, 0)): 

        self.init_state = np.asarray(init_state, dtype='float')

        self.params = (L1, L2, M1, M2, G)

        self.origin = origin

        self.time_elapsed = 0


        self.state = self.init_state * np.pi / 180.

    

    def position(self):

        """compute the current x,y positions of the pendulum arms"""

        (L1, L2, M1, M2, G) = self.params


        x = np.cumsum([self.origin[0],

                       L1 * sin(self.state[0]),

                       L2 * sin(self.state[2])])

        y = np.cumsum([self.origin[1],

                       -L1 * cos(self.state[0]),

                       -L2 * cos(self.state[2])])

        return (x, y)


    def energy(self):

        """compute the energy of the current state"""

        (L1, L2, M1, M2, G) = self.params


        x = np.cumsum([L1 * sin(self.state[0]),

                       L2 * sin(self.state[2])])

        y = np.cumsum([-L1 * cos(self.state[0]),

                       -L2 * cos(self.state[2])])

        vx = np.cumsum([L1 * self.state[1] * cos(self.state[0]),

                        L2 * self.state[3] * cos(self.state[2])])

        vy = np.cumsum([L1 * self.state[1] * sin(self.state[0]),

                        L2 * self.state[3] * sin(self.state[2])])


        U = G * (M1 * y[0] + M2 * y[1])

        K = 0.5 * (M1 * np.dot(vx, vx) + M2 * np.dot(vy, vy))


        return U + K


    def dstate_dt(self, state, t):

        """compute the derivative of the given state"""

        (M1, M2, L1, L2, G) = self.params


        dydx = np.zeros_like(state)

        dydx[0] = state[1]

        dydx[2] = state[3]


        cos_delta = cos(state[2] - state[0])

        sin_delta = sin(state[2] - state[0])


        den1 = (M1 + M2) * L1 - M2 * L1 * cos_delta * cos_delta

        dydx[1] = (M2 * L1 * state[1] * state[1] * sin_delta * cos_delta

                   + M2 * G * sin(state[2]) * cos_delta

                   + M2 * L2 * state[3] * state[3] * sin_delta

                   - (M1 + M2) * G * sin(state[0])) / den1


        den2 = (L2 / L1) * den1

        dydx[3] = (-M2 * L2 * state[3] * state[3] * sin_delta * cos_delta

                   + (M1 + M2) * G * sin(state[0]) * cos_delta

                   - (M1 + M2) * L1 * state[1] * state[1] * sin_delta

                   - (M1 + M2) * G * sin(state[2])) / den2

        

        return dydx


    def step(self, dt):

        """execute one time step of length dt and update state"""

        self.state = integrate.odeint(self.dstate_dt, self.state, [0, dt])[1]

        self.time_elapsed += dt


#------------------------------------------------------------

# set up initial state and global variables

pendulum = DoublePendulum([180., 0.0, -20., 0.0])

dt = 1./30 # 30 fps


#------------------------------------------------------------

# set up figure and animation

fig = plt.figure()

ax = fig.add_subplot(111, aspect='equal', autoscale_on=False,

                     xlim=(-2, 2), ylim=(-2, 2))

ax.grid()


line, = ax.plot([], [], 'o-', lw=2)

time_text = ax.text(0.02, 0.95, '', transform=ax.transAxes)

energy_text = ax.text(0.02, 0.90, '', transform=ax.transAxes)


def init():

    """initialize animation"""

    line.set_data([], [])

    time_text.set_text('')

    energy_text.set_text('')

    return line, time_text, energy_text


def animate(i):

    """perform animation step"""

    global pendulum, dt

    pendulum.step(dt)

    

    line.set_data(*pendulum.position())

    time_text.set_text('time = %.1f' % pendulum.time_elapsed)

    energy_text.set_text('energy = %.3f J' % pendulum.energy())

    return line, time_text, energy_text


# choose the interval based on dt and the time to animate one step

from time import time

t0 = time()

animate(0)

t1 = time()

interval = 1000 * dt - (t1 - t0)


ani = animation.FuncAnimation(fig, animate, frames=300,

                              interval=interval, blit=True, init_func=init)


# save the animation as an mp4.  This requires ffmpeg or mencoder to be

# installed.  The extra_args ensure that the x264 codec is used, so that

# the video can be embedded in html5.  You may need to adjust this for

# your system: for more information, see

# http://matplotlib.sourceforge.net/api/animation_api.html

#ani.save('double_pendulum.mp4', fps=30, extra_args=['-vcodec', 'libx264'])


plt.show()

PYTHON - TKINTER - CANVAS - ANIMATION

 



import tkinter as tk

import random as rd


class AppliBaballe(tk.Tk):

    def __init__(self):

        

        tk.Tk.__init__(self)

        # Coord baballe.

        self.x, self.y = 200, 200

        # Rayon baballe.

        self.size = 50

        # Pas de deplacement.

        self.dx, self.dy = 20, 20

        

        self.canv = tk.Canvas(self, bg='light gray', height=400, width=400)

        self.canv.pack()

        

        self.baballe = self.canv.create_oval(self.x, self.y,

                                             self.x+self.size,

                                             self.y+self.size,

                                             width=2, fill="blue")

        # Binding des actions.

        self.canv.bind("<Button-1>", self.incr)

        self.canv.bind("<Button-2>", self.boom)

        self.canv.bind("<Button-3>", self.decr)

        self.bind("<Escape>", self.stop)

        # Lancer la baballe.

        self.move()


    def move(self):

        

        

        self.x += self.dx

        self.y += self.dy

        

        if self.x < 10:

            self.dx = abs(self.dx)

        if self.x > 400-self.size-10:

            self.dx = -abs(self.dx)

        if self.y < 10:

            self.dy = abs(self.dy)

        if self.y > 400-self.size-10:

            self.dy = -abs(self.dy)

        

        self.canv.coords(self.baballe, self.x, self.y, self.x+self.size,

                         self.y+self.size)

        

        self.after(50, self.move)


    def boom(self, mclick):

        

        self.x = mclick.x

        self.y = mclick.y

        self.canv.create_text(self.x, self.y, text="Boom !", fill="red")

        self.dx = rd.choice([-30, -20, -10, 10, 20, 30])

        self.dy = rd.choice([-30, -20, -10, 10, 20, 30])


    def incr(self, lclick):

        

        self.size += 10

        if self.size > 200:

            self.size = 200


    def decr(self, rclick):

        

        self.size -= 10

        if self.size < 10:

            self.size = 10


    def stop(self, esc):

        

        self.quit()



if __name__ == "__main__":

    myapp = AppliBaballe()

    myapp.title("Baballe !")

    myapp.mainloop()

PYTHON - TKINTER - CANVAS

 



import tkinter as tk

import random as rd


class AppliCanevas(tk.Tk):

    def __init__(self):

        tk.Tk.__init__(self)

        self.size = 500

        self.creer_widgets()


    def creer_widgets(self):

        

        self.canv = tk.Canvas(self, bg="light gray", height=self.size,

                              width=self.size)

        self.canv.pack(side=tk.LEFT)

        # boutons

        self.bouton_cercles = tk.Button(self, text="Cercle !",

                                        command=self.dessine_cercles)

        self.bouton_cercles.pack(side=tk.TOP)

        self.bouton_lignes = tk.Button(self, text="Lignes !",

                                       command=self.dessine_lignes)

        self.bouton_lignes.pack()

        self.bouton_quitter = tk.Button(self, text="Quitter",

                                        command=self.quit)

        self.bouton_quitter.pack(side=tk.BOTTOM)


    def rd_col(self):

        return rd.choice(("black", "red", "green", "blue", "yellow", "magenta",

                          "cyan", "white", "purple"))


    def dessine_cercles(self):

        for i in range(20):

            x, y = [rd.randint(1, self.size) for j in range(2)]

            diameter = rd.randint(1, 50)

            self.canv.create_oval(x, y, x+diameter, y+diameter,

                                  fill=self.rd_col())


    def dessine_lignes(self):

        for i in range(20):

            x, y, x2, y2 = [rd.randint(1, self.size) for j in range(4)]

            self.canv.create_line(x, y, x2, y2, fill=self.rd_col())



if __name__ == "__main__":

    app = AppliCanevas()

    app.title("abc")

    app.mainloop()