Python用モジュール「Tkinter」でボタンを設置する方法についてソースコード付きでまとめました。
Tkinterでボタンの設置
Pythonの標準モジュール「Tkinter」を用いて、ボタンを設置します。
サンプルコード(Python3)
サンプルプログラムのソースコードです。
# -*- coding:utf-8 -*-
import tkinter
class Application(tkinter.Frame):
def __init__(self, master=None):
super().__init__(master)
self.pack()
self.create_widgets()
# ウィジェットの作成
def create_widgets(self):
# 「はい」ボタンの生成
self.yes = tkinter.Button(self)
self.yes["text"] = "はい" # ボタンのテキスト
self.yes["command"] = self.print_yes # ボタンが押されたらprint_yesメソッドを実行
self.yes.pack(side="top") # ボタンの位置
# 「終了」ボタンの作成
self.quit = tkinter.Button(self, text="終了", command=self.master.destroy)
self.quit.pack(side="bottom") # ボタンの位置
def print_yes(self):
print("はいが押されました")
root = tkinter.Tk()
root.geometry("300x300")
app = Application(master=root)
app.mainloop()
tkinter.Frameの継承クラスを作ります。
そして、クラス内でボタンオブジェクト「tkinter.Button」をpackします。
packのside引数(‘left’, ‘right’, ‘top’, ‘bottom’)でボタンの位置を指定できます。
実行結果
サンプルプログラムの実行結果です。


【Tkinter入門】PythonでGUIアプリケーションを簡単に作ろう
Python用モジュール「Tkinter」でGUIアプリを作成する方法についてソースコード付きでまとめました。

404 NOT FOUND | Python超入門速報

【Python超入門】基礎から応用例まで幅広く解説
PythonについてPythonは、統計処理や機械学習、ディープラーニングといった数値計算分野を中心に幅広い用途で利用されているプログラミング言語です。他のプログラミング言語と比較して「コードが短くて読みやすい、書きやすい」「ライブラリが豊...

コメント