Pythonでタイマーを使うには
【環境条件】
OS:Windows 10
Python 3.6.1
【サンプルリスト】
# coding:utf-8
import tkinter as tk
# 円の座標と半径
x = 400
y = 300
# 移動量
dx = 1
#タイマー関数
def move():
global x, y, dx
# いまの円を消す
canvas.create_oval(x - 20, y - 20, x + 20, y + 20, fill="white", width=0)
# X座標を動かす
x = x + dx
# 次の位置に円を描く
canvas.create_oval(x - 20, y - 20, x + 20, y + 20, fill="red", width=0)
# 端を超えていたら反対向きにする
if x >= canvas.winfo_width():←キャンパスの幅
dx = -1
if x <= 0:
dx = +1
# 再びタイマー
root.after(10, move)←0.01秒後に、move関数を動かす
# ウィンドウを描く
root = tk.Tk()
root.geometry("600x400")
root.title("タイマー")
# キャンバスを置く
canvas =tk.Canvas(root, width =600, height =400, bg="white")
canvas.place(x = 0, y = 0)
# タイマーを設定する
root.after(10, move)←0.01秒後に、move関数を動かす
root.mainloop()
【tkinterのタイマー機能について】
☆afterメソッド
after(時間, 実行したい関数)
時間は1000分の1秒単位(ミリ秒)で指定する。
【結果】
自動で赤玉が動き、壁に当たると反転する

※コメント投稿者のブログIDはブログ作成者のみに通知されます