Minggu, 12 Oktober 2025
Jumat, 10 Oktober 2025
WXPYTHON - import AnimationCtrl, Animation - Menampilkan File Animasi Gif
import wx
from wx.adv import AnimationCtrl, Animation
app=wx.App()
frame = wx.Frame(None, -1, title='2', pos=(0, 0), size=(200, 200))
app.SetTopWindow(frame)
anim = Animation(r'C:\Users\Acer\Pictures\animt.gif')
anim_ctrl = AnimationCtrl(frame, -1, anim)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(anim_ctrl)
frame.SetSizerAndFit(sizer)
frame.Show()
anim_ctrl.Play()
app.MainLoop()
PYTHON - TKINTER - NUMPY
import tkinter
import numpy as np
# Implement the default Matplotlib key bindings.
from matplotlib.backend_bases import key_press_handler
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg,
NavigationToolbar2Tk)
from matplotlib.figure import Figure
root = tkinter.Tk()
root.wm_title("Embedded in Tk")
fig = Figure(figsize=(5, 4), dpi=100)
t = np.arange(0, 3, .01)
ax = fig.add_subplot()
line, = ax.plot(t, 2 * np.sin(2 * np.pi * t))
ax.set_xlabel("time [s]")
ax.set_ylabel("f(t)")
canvas = FigureCanvasTkAgg(fig, master=root) # A tk.DrawingArea.
canvas.draw()
# pack_toolbar=False will make it easier to use a layout manager later on.
toolbar = NavigationToolbar2Tk(canvas, root, pack_toolbar=False)
toolbar.update()
canvas.mpl_connect(
"key_press_event", lambda event: print(f"you pressed {event.key}"))
canvas.mpl_connect("key_press_event", key_press_handler)
button_quit = tkinter.Button(master=root, text="Quit", command=root.destroy)
def update_frequency(new_val):
# retrieve frequency
f = float(new_val)
# update data
y = 2 * np.sin(2 * np.pi * f * t)
line.set_data(t, y)
# required to update canvas and attached toolbar!
canvas.draw()
slider_update = tkinter.Scale(root, from_=1, to=5, orient=tkinter.HORIZONTAL,
command=update_frequency, label="Frequency [Hz]")
# Packing order is important. Widgets are processed sequentially and if there
# is no space left, because the window is too small, they are not displayed.
# The canvas is rather flexible in its size, so we pack it last which makes
# sure the UI controls are displayed as long as possible.
button_quit.pack(side=tkinter.BOTTOM)
slider_update.pack(side=tkinter.BOTTOM)
toolbar.pack(side=tkinter.BOTTOM, fill=tkinter.X)
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=True)
tkinter.mainloop()
WXPYTHON - BoxSizer
import wx
class MyFrame(wx.Frame):
def __init__(self, parent, title):
super(MyFrame, self).__init__(parent, title=title, size=(300, 200))
panel = wx.Panel(self)
vbox = wx.BoxSizer(wx.VERTICAL)
# Add a text control
text_ctrl = wx.TextCtrl(panel)
vbox.Add(text_ctrl, proportion=0, flag=wx.EXPAND | wx.ALL, border=5)
# Add some buttons
hbox = wx.BoxSizer(wx.HORIZONTAL)
btn1 = wx.Button(panel, label='Button 1')
btn2 = wx.Button(panel, label='Button 2')
hbox.Add(btn1, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)
hbox.Add(btn2, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)
vbox.Add(hbox, proportion=1, flag=wx.EXPAND)
panel.SetSizer(vbox)
self.Centre()
self.Show()
app = wx.App()
frame = MyFrame(None, "Geometry Example")
app.MainLoop()
WXPYTHON - MessageBox
import wx
class MyFrame(wx.Frame):
def __init__(self):
super().__init__(parent=None, title='My wxPython App with Sizers')
panel = wx.Panel(self)
# Create a vertical box sizer
vbox = wx.BoxSizer(wx.VERTICAL)
# Add a StaticText
text_label = wx.StaticText(panel, label="Enter your name:")
vbox.Add(text_label, 0, wx.ALL | wx.EXPAND, 5) # Add with padding and expansion
# Add a TextCtrl
self.name_input = wx.TextCtrl(panel)
vbox.Add(self.name_input, 0, wx.ALL | wx.EXPAND, 5)
# Add a Button
greet_button = wx.Button(panel, label="Greet")
greet_button.Bind(wx.EVT_BUTTON, self.on_greet)
vbox.Add(greet_button, 0, wx.ALL | wx.CENTER, 5)
panel.SetSizer(vbox) # Set the sizer for the panel
self.Layout() # Re-calculate layout
self.Show()
def on_greet(self, event):
name = self.name_input.GetValue()
if name:
wx.MessageBox(f"Hello, {name}!", "Greeting", wx.OK | wx.ICON_INFORMATION)
else:
wx.MessageBox("Please enter your name.", "Warning", wx.OK | wx.ICON_WARNING)
if __name__ == '__main__':
app = wx.App()
frame = MyFrame()
app.MainLoop()
WXPYTHON - CALCULATOR
import wx
class Interface(wx.Frame):
def __init__(self, parent, title):
super(Interface, self).__init__(parent, title=title, size=(300, 400))
# Show the window on screen
self.setup()
self.Show()
def setup(self):
box = wx.BoxSizer(wx.VERTICAL)
self.textbox = wx.TextCtrl(self, style=wx.TE_RIGHT)
box.Add(self.textbox, flag=wx.EXPAND | wx.TOP | wx.BOTTOM, border=4)
grid = wx.GridSizer(5, 4, 10, 10)
buttons = [
'7', '8', '9', '/',
'4', '5', '6', '*',
'1', '2', '3', '-',
'0', '.', 'C', '+',
'='
]
for label in buttons:
button = wx.Button(self, -1, label)
grid.Add(button, 0, wx.EXPAND)
self.Bind(wx.EVT_BUTTON, self.on_button_press, button)
box.Add(grid, proportion=1, flag=wx.EXPAND)
self.SetSizer(box)
def on_button_press(self, e):
# Get label of button
label = e.GetEventObject().GetLabel()
# Get the input from the TextCtrl
calculation = self.textbox.GetValue()
# Handle the event based on the button pressed
if label == '=': # Calculate the result of the input in the TextCtrl
# Ignore an empty calculation
if not calculation:
return
try:
# Calculate the result
result = eval(calculation)
except SyntaxError as err: # Catch any input errors (e.g. '6 +* 2')
wx.LogError('Invalid syntax ({}). Please check your input and try again.'.format(calculation))
return
except NameError as err: # Catch any manually typed errors (e.g. '2 x three')
wx.LogError('There was a error. Please check your input and try again.')
return
# Show the result
self.textbox.SetValue(str(result))
elif label == 'C': # Clear the TextCtrl
self.textbox.SetValue('')
else: # 0-9 (and .)
# Add the label of the button press to the current calculation in the TextCtrl
self.textbox.SetValue(calculation + label)
if __name__ == '__main__':
# Create the application object
app = wx.App()
Interface(None, title='Calculator')
app.MainLoop()
WXPYTHON - TEXT ANIMATION
import wx
class TextAnimationFrame(wx.Frame):
def __init__(self, parent, title):
super().__init__(parent, title=title, size=(500, 200))
panel = wx.Panel(self)
vbox = wx.BoxSizer(wx.VERTICAL)
self.animated_text = wx.StaticText(panel, label="", style=wx.ALIGN_CENTER)
font = wx.Font(18, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD)
self.animated_text.SetFont(font)
vbox.Add(self.animated_text, 1, wx.EXPAND | wx.ALL, 20)
panel.SetSizer(vbox)
self.Layout()
self.text_to_animate = ".......................Hello, wxPython!"
self.current_char_index = 0
self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.on_timer, self.timer)
self.timer.Stop()
self.timer.Start(200) # Update every 100 milliseconds
def on_timer(self, event):
if self.current_char_index < len(self.text_to_animate):
current_displayed_text = self.text_to_animate[:self.current_char_index + 1]
self.animated_text.SetLabel(current_displayed_text)
self.current_char_index += 1
else:
self.timer.Stop() # Stop the timer once animation is complete
# Optional: Reset or loop the animation
# self.current_char_index = 0
# self.timer.Start(100)
if __name__ == '__main__':
app = wx.App()
frame = TextAnimationFrame(None, "wxPython Text Animation")
frame.Show()
app.MainLoop()
WXPYTHON - import time 2
import wx
import threading
import time
class MyFrame( wx.Frame ):
def __init__( self, parent ):
wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = u"Seconds Counter",
pos = wx.DefaultPosition, size = wx.Size( 236,173 ),
style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )
self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize )
self.SetBackgroundColour( wx.Colour( 0, 0, 255 ) )
bSizer1 = wx.BoxSizer( wx.VERTICAL )
self.m_textCtrl = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,
wx.DefaultSize, 0 )
self.m_textCtrl.SetFont( wx.Font( 20, 74, 90, 92, False, "Comic Sans MS" ) )
bSizer1.Add( self.m_textCtrl, 0, wx.ALL, 5 )
self.m_button_start = wx.Button( self, wx.ID_ANY, u"Start", wx.DefaultPosition,
wx.DefaultSize, 0 )
bSizer1.Add( self.m_button_start, 0, wx.ALL, 5 )
self.m_button_stop = wx.Button( self, wx.ID_ANY, u"Stop", wx.DefaultPosition,
wx.DefaultSize, 0 )
bSizer1.Add( self.m_button_stop, 0, wx.ALL, 5 )
self.SetSizer( bSizer1 )
self.Layout()
# Connect Events
self.m_button_start.Bind( wx.EVT_LEFT_DOWN, self.m_button_startOnLeftDown )
self.m_button_stop.Bind( wx.EVT_LEFT_DOWN, self.m_button_stopOnLeftDown )
def m_button_startOnLeftDown( self, event ):
self.counter = Counter(0, 1, self.m_textCtrl)
self.counter.start()
pass
def m_button_stopOnLeftDown( self, event ):
count = self.counter.finish()
print(count) # test
pass
class Counter(threading.Thread):
"""
create a thread object that will do the counting in a separate thread
"""
def __init__(self, value, increment, display_widget):
# init the thread
threading.Thread.__init__(self)
# initial value
self.value = value
# amount to increment
self.increment = increment
# controls the while loop in the run command
self.alive = False
# display widget
self.display = display_widget
def run(self):
"this will run in a separate thread"
self.alive = True
while self.alive:
# delay for 1 second
time.sleep(1)
self.value += self.increment
print(self.value) # test
self.display.SetValue(str(self.value))
def peek(self):
"return the current value"
return self.value
def finish(self):
"close the thread, return final value"
# stop the while loop in 'run'
self.alive = False
return self.value
app = wx.App(0)
# create a MyFrame instance and show the frame
frame = MyFrame(None)
frame.Center()
frame.Show()
app.MainLoop()
WXPYTHON - SpacerExample
import wx
class SpacerExample(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title = "Spacer example", size = (350, 370))
panel = wx.Panel(self)
font = wx.Font(20, wx.SWISS, wx.NORMAL, wx.NORMAL, False, "Mangal")
title = wx.StaticText(panel, label = "Border using sizers", style = wx.ALIGN_CENTRE)
title.SetFont(font)
set1text = wx.StaticText(panel, label = "Please enter something")
set1box = wx.TextCtrl(panel)
set2text = wx.StaticText(panel , label = "Please enter something else")
set2box = wx.TextCtrl(panel)
set3text = wx.StaticText(panel, label = "Please enter something else again")
set3box = wx.TextCtrl(panel)
save = wx.Button(panel, label = "Save")
cancel = wx.Button(panel, label = "Cancel")
#these are my spaces in the main column
topspace = wx.BoxSizer()
vertspc1 = wx.BoxSizer()
vertspc2 = wx.BoxSizer()
vertspc3 = wx.BoxSizer()
vertspc4 = wx.BoxSizer()
vertspc5 = wx.BoxSizer()
#these spacers are my right and left borders
hzlspc1 = wx.BoxSizer()
hzlspc2 = wx.BoxSizer()
#this is the space between my buttons
hzlspc3 = wx.BoxSizer()
buttonarr = wx.BoxSizer()
buttonarr.Add(cancel, proportion = 3, flag = wx.EXPAND)
buttonarr.Add(hzlspc3, proportion = 1)
buttonarr.Add(save, proportion = 3, flag = wx.EXPAND)
#this organises the main column of my programme
mainsizer = wx.BoxSizer(wx.VERTICAL)
mainsizer.Add(topspace, proportion = 1)
mainsizer.Add(title, proportion = 4, flag = wx.EXPAND)
mainsizer.Add(vertspc1, proportion = 1)
mainsizer.Add(set1text, proportion = 2)
mainsizer.Add(set1box, proportion = 2, flag = wx.EXPAND)
mainsizer.Add(vertspc2, proportion = 2)
mainsizer.Add(set2text, proportion = 2)
mainsizer.Add(set2box, proportion = 2, flag = wx.EXPAND)
mainsizer.Add(vertspc3, proportion = 2)
mainsizer.Add(set3text, proportion = 2)
mainsizer.Add(set3box, proportion = 2, flag = wx.EXPAND)
mainsizer.Add(vertspc4, proportion = 2)
mainsizer.Add(buttonarr, proportion = 2, flag = wx.EXPAND)
mainsizer.Add(vertspc5, proportion = 2)
#this adds the left and right border
layout = wx.BoxSizer()
layout.Add(hzlspc1, proportion = 1)
layout.Add(mainsizer, proportion = 8)
layout.Add(hzlspc2, proportion = 1)
#this sets the sizers in action, i only need to set the top one
panel.SetSizer(layout)
app = wx.App(redirect=False)
window = SpacerExample()
window.Show()
app.MainLoop()
WXPYTHON - import time
import wx
import wx.gizmos
import time
class LedClock(wx.Frame):
"""
create an LED clock showing the current time
"""
def __init__(self, parent=None):
wx.Frame.__init__(self, parent, -1, title='LED Clock',
size=(320, 100))
# default colors are green on black
self.led = wx.gizmos.LEDNumberCtrl(self, -1,
style=wx.gizmos.LED_ALIGN_CENTER)
# set up a timer
self.timer = wx.Timer(self, -1)
# update clock digits every second (1000ms)
self.timer.Start(1000)
# bind the timer to a method
self.Bind(wx.EVT_TIMER, self.update_clock)
def update_clock(self, event):
# get the current time tuple from the computer
current = time.localtime(time.time())
# time string can have characters 0..9, -, period, or space
ts = time.strftime("%H %M %S", current)
self.led.SetValue(ts)
app = wx.App(0)
LedClock().Show()
app.MainLoop()
WXPYTHON - import math
from tkinter import *
import math
def particleCount(decay, p0, time):
p = (p0*math.e)**(-(decay*time))
return (p)
# define root window
root = Tk()
root.title("Radioactive Decay Graph")
# create frame to put control buttons onto
frame = Frame(root, bg='grey', width=400, height=40)
frame.pack(fill='x')
button1 = Button(frame, text='Button1')
button1.pack(side='left', padx=10)
button2 = Button(frame, text='Button2')
button2.pack(side='left')
# set canvas properties
width = 400
height = 400
center = height*(5/6)
x_increment = 1
# invoke canvas
c = Canvas(root, width=width, height=height, bg='black')
c.pack()
# add string
str1 = "Logarithmic decay graph"
c.create_text(10, 20, anchor=SW, text=str1)
# line width stretch
x_factor = 1
# line height stretch
y_amplitude = -300
center_line = c.create_line(0, center +1, width, center+1, fill='green')
coordinates = []
coord = []
for x in range(0, 600):
# x coordinates
coord.append((x * x_increment) * x_factor)
# y coordinates
y = particleCount((1.16*(10**-3)), (5*(10**6)), x)
coord.append((y * y_amplitude) + center)
coordinates.append(coord)
coord = []
log_line = c.create_line(coordinates, fill='red')
root.mainloop()
PYTHON - KIVY - import Animation
# work same as kivy.App used to run the App
from kivy.base import runTouchApp
# to use .kv file as a string we have to import it
from kivy.lang import Builder
# A Widget is the base building block of GUI interfaces in Kivy
from kivy.uix.widget import Widget
# The Clock object allows you to schedule a
# function call in the future
from kivy.clock import Clock
# Animation and AnimationTransition are
# used to animate Widget properties
from kivy.animation import Animation
# The Properties classes are used when
# you create an EventDispatcher.
from kivy.properties import ListProperty
# Core class for creating the default Kivy window.
from kivy.core.window import Window
# As name suggest used when random things required
from random import random
# load the kv file as string
Builder.load_string('''
<Root>:
# Setting the position (initial) of boxes
ClockRect:
pos: 300, 300
AnimRect:
pos: 500, 300
# creation and animation of red box
<ClockRect>:
canvas:
Color:
rgba: 1, 0, 0, 1
Rectangle:
pos: self.pos
size: self.size
# creation and animation of red box
<AnimRect>:
canvas:
Color:
rgba: 0, 1, 0, 1
Rectangle:
pos: self.pos
size: self.size
''')
# Create the root class
class Root(Widget):
pass
# Create the clock class Then is when clicked
# how much time to animate
# the red colour block animation is created by it
class ClockRect(Widget):
velocity = ListProperty([10, 15])
def __init__(self, **kwargs):
super(ClockRect, self).__init__(**kwargs)
Clock.schedule_interval(self.update, 1 / 60.)
def update(self, *args):
self.x += self.velocity[0]
self.y += self.velocity[1]
if self.x < 0 or (self.x + self.width) > Window.width:
self.velocity[0] *= -1
if self.y < 0 or (self.y + self.height) > Window.height:
self.velocity[1] *= -1
# Create the Animation class
# And add animation
# green colour box is animated through this class
class AnimRect(Widget):
def anim_to_random_pos(self):
Animation.cancel_all(self)
random_x = random() * (Window.width - self.width)
random_y = random() * (Window.height - self.height)
anim = Animation(x = random_x, y = random_y,
duration = 4,
t ='out_elastic')
anim.start(self)
def on_touch_down(self, touch):
if self.collide_point(*touch.pos):
self.anim_to_random_pos()
# run the App
runTouchApp(Root())
PYTHON - KIVY - import kivy_garden.contextmenu
import kivy
from kivy.app import App
from kivy.lang import Builder
import kivy_garden.contextmenu
kv = """
FloatLayout:
id: layout
AppMenu:
id: app_menu
top: root.height
cancel_handler_widget: layout
AppMenuTextItem:
text: "Menu #1"
ContextMenu:
ContextMenuTextItem:
text: "Item #11"
ContextMenuTextItem:
text: "Item #12"
AppMenuTextItem:
text: "Menu Menu Menu #2"
ContextMenu:
ContextMenuTextItem:
text: "Item #21"
ContextMenuTextItem:
text: "Item #22"
ContextMenuTextItem:
text: "ItemItemItem #23"
ContextMenuTextItem:
text: "Item #24"
ContextMenu:
ContextMenuTextItem:
text: "Item #241"
ContextMenuTextItem:
text: "Hello, World!"
on_release: app.say_hello(self.text)
# ...
ContextMenuTextItem:
text: "Item #5"
AppMenuTextItem:
text: "Menu Menu #3"
ContextMenu:
ContextMenuTextItem:
text: "SubMenu #31"
ContextMenuDivider:
ContextMenuTextItem:
text: "SubMenu #32"
# ...
AppMenuTextItem:
text: "Menu #4"
# ...
# The rest follows as usually
"""
class MyApp(App):
def build(self):
self.title = 'Simple app menu example'
return Builder.load_string(kv)
def say_hello(self, text):
print(text)
self.root.ids['app_menu'].close_all()
if __name__ == '__main__':
MyApp().run()
PYTHON - KIVY - import DropDown 3
from kivy.app import App
from kivy.uix.dropdown import DropDown
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.core.window import Window
from kivy.uix.label import Label
Window.clearcolor = (0.9, 0.9, 1, 1)
class DropdownTextInputExample(Widget):
def __init__(self, **kwargs):
super().__init__(**kwargs)
center_x = Window.width / 2
self.input = TextInput(text='', size_hint=(None,None), width=200, height=40,pos=(center_x - 150, Window.height - 60))
self.add_widget(self.input)
dropdown = DropDown()
for val in ['Apple', 'Banana', 'Cherry']:
btn = Button(text=val, size_hint_y=None, height=40)
btn.bind(on_release=lambda btn, v=val: dropdown.select(v))
dropdown.add_widget(btn)
mainbtn = Button(text='Select Fruit', size_hint=(None,None), width=120, height=40,pos=(center_x + 60, Window.height - 60))
mainbtn.bind(on_release=dropdown.open)
dropdown.bind(on_select=lambda instance, x: setattr(self.input, 'text', x))
self.add_widget(mainbtn)
class DropdownApp(App):
def build(self):
return DropdownTextInputExample()
if __name__ == '__main__':
DropdownApp().run()
PYHTON - KIVY 2 - import DropDown 2
from kivy.app import App
from kivy.uix.dropdown import DropDown
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.core.window import Window
from kivy.uix.label import Label
Window.clearcolor = (0.95, 0.95, 0.95, 1)
class DropdownLabelExample(Widget):
def __init__(self, **kwargs):
super().__init__(**kwargs)
center_x = Window.width / 2
self.lbl = Label(text='Selected: None', color=(0, 0, 0, 1),pos=(center_x - 50, Window.height - 140))
self.add_widget(self.lbl)
dropdown = DropDown()
for val in ['Red', 'Green', 'Blue']:
btn = Button(text=val, size_hint_y=None, height=40)
btn.bind(on_release=lambda btn, v=val: dropdown.select(v))
dropdown.add_widget(btn)
mainbtn = Button(text='Select Color', size_hint=(None, None), width=120, height=40,pos=(center_x - 60, Window.height - 190))
mainbtn.bind(on_release=dropdown.open)
dropdown.bind(on_select=lambda instance, x: setattr(self.lbl, 'text', f'Selected: {x}'))
self.add_widget(mainbtn)
class DropdownApp(App):
def build(self):
return DropdownLabelExample()
if __name__ == '__main__':
DropdownApp().run()
PYTHON - KIVY - import DropDown
from kivy.app import App
from kivy.uix.dropdown import DropDown
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.core.window import Window
Window.clearcolor = (1, 1, 1, 1) # white background
class TopDropdown(Widget):
def __init__(self, **kwargs):
super().__init__(**kwargs)
center_x = Window.width / 2
self.input = TextInput(text='Select',size_hint=(None,None), width=200, height=40,pos=(center_x - 150, Window.height
- 60))
self.add_widget(self.input)
dropdown = DropDown()
for val in ['Option 1','Option 2','Option 3']:
btn = Button(text=val, size_hint_y=None, height=40)
btn.bind(on_release=lambda btn, v=val: dropdown.select(v))
dropdown.add_widget(btn)
mainbtn = Button(text='Choose', size_hint=(None,None), width=100, height=40,pos=(center_x + 60, Window.height -
60))
mainbtn.bind(on_release=dropdown.open)
dropdown.bind(on_select=lambda instance, x: setattr(self.input,'text',x))
self.add_widget(mainbtn)
class DropdownApp(App):
def build(self):
return TopDropdown()
if __name__ == '__main__':
DropdownApp().run()
Senin, 06 Oktober 2025
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()