6
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Tkinterのラベルを書き換える方法

Posted at

はじめに

pythonのGUI作成ライブラリ『tkinter』で、
ボタンを押したときにラベルが書き換わるという処理の書き方が分からずに困った。

テキストボックスに入力した数値を受け取り、平均を出力するアプリを作る、という本来の目的・内容に合わせてその対処法を書いていく。

環境

Python 3.6.8

処理方法

wordsという変数名のラベルを"rewrited"と書き換える場合、
ボタンを押したときの処理の中で、

words["text"] = "rewrited"

と書き加えてやればよい。

より具体的な説明、というよりコード例

import tkinter as tk

root = tk.Tk()
root.title(u"平均算出アプリ")
root.geometry("400x300")


# ボタンを押したときの処理

def buttoneffect(event):
    value = textbox.get()
    split_value = value.split(",")
    int_values = list(map(int, split_value))
    average = sum(int_values) / len(int_values)

    textbox.delete(0, tk.END)  # テキストボックスの中身を初期化する
    words4["text"] = "平均値は%sです。" % average  # ラベルの中身を書き換える


# ボタンやテキストボックスの配置

words = tk.Label(text=u"入力された値の平均値を算出します。", font=("", 12))
words.pack()

words2 = tk.Label(text=u"カンマ区切りで数値を入力してください。", font=("", 12))
words2.pack()

textbox = tk.Entry()
textbox.insert(tk.END, "Input this box.")
textbox.place(x=140, y=70)

button = tk.Button(text=u"計算する")
button.bind("<Button-1>", buttoneffect)
button.place(x=150, y=100)

words3 = tk.Label(text=u"統計データ", font=("", 12))
words3.place(x=50, y=140)

words4 = tk.Label(text=u" ", font=("", 12))  # 平均値の出力に利用する空のラベル
words4.place(x=140, y=160)


root.mainloop()

参考

PythonのTkinterを使ってみる
https://qiita.com/nnahito/items/ad1428a30738b3d93762

Tkinter ラベルテキストを変更する方法
https://www.delftstack.com/ja/howto/python-tkinter/how-to-change-the-tkinter-label-text/

6
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?