Tkinter ボタンのテキストを更新する方法

このチュートリアルでは、Tkinter ボタンのテキストを変更する方法を紹介します。これは、Tkinter ラベルテキストを変更するメソッドに似ています、
StringVar
メソッド- ボタンの
text
プロパティメソッド
Tkinter ボタンのテキストを変更するには、StringVar
を使用する
StringVar
は、Tkinter 文字列変数を作成する Tkinter コンストラクターの一種です。
StringVar
変数を Tkinter Button
ウィジェットに関連付けた後、変数が変更されると、Tkinter はこの Button
のテキストを更新します。
import tkinter as tk
class Test():
def __init__(self):
self.root = tk.Tk()
self.root.geometry("250x100")
self.text = tk.StringVar()
self.text.set("Original Text")
self.buttonA = tk.Button(self.root, textvariable=self.text)
self.buttonB = tk.Button(self.root,
text="Click to change text",
command=self.changeText)
self.buttonA.pack(side=tk.LEFT)
self.buttonB.pack(side=tk.RIGHT)
self.root.mainloop()
def changeText(self):
self.text.set("Updated Text")
app=Test()
self.text = tk.StringVar()
self.text.set("Original Text")
Tkinter コンストラクターは、self.text = tk.StringVar("Text")
のような文字列で文字列変数を開始できません。
self.text.set("Original Text")
のように、set
メソッドを呼び出して StringVar
値を設定する必要があります。
self.buttonA = tk.Button(self.root, textvariable=self.text)
StringVar
変数 self.text
は、self.buttonA
のオプション textvariable
に割り当てられています。Tkinter は、self.text
が変更されると、self.buttonA
のテキストを自動的に更新します。
ボタンのテキストを変更する Tkinter Button の text
プロパティ
Tkinter ボタンのテキストを変更する別の解決策は、ボタンの text
プロパティを変更することです。
import tkinter as tk
class Test():
def __init__(self):
self.root = tk.Tk()
self.root.geometry("250x100")
self.buttonA = tk.Button(self.root,
text="Original Text")
self.buttonB = tk.Button(self.root,
text="Click to change text",
command=self.changeText)
self.buttonA.pack(side=tk.LEFT)
self.buttonB.pack(side=tk.RIGHT)
self.root.mainloop()
def changeText(self):
self.buttonA['text'] = "Updated Text"
app=Test()
text
は Button
オブジェクトのキーの 1つで、そのテキストは text="Original Text"
で開始でき、新しい値を text
に割り当てることで更新することもできます。
以下に示すように、tk.Button.configure()
メソッドは、text
プロパティを変更して Tkinter Button
のテキストを変更することもできます。
import tkinter as tk
class Test():
def __init__(self):
self.root = tk.Tk()
self.root.geometry("250x100")
self.buttonA = tk.Button(self.root,
text="Original Text")
self.buttonB = tk.Button(self.root,
text="Click to change text",
command=self.changeText)
self.buttonA.pack(side=tk.LEFT)
self.buttonB.pack(side=tk.RIGHT)
self.root.mainloop()
def changeText(self):
self.buttonA.configure(text = "Updated Text")
app=Test()
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn関連記事 - Tkinter Button
- Tkinter ボタンコマンドに引数を渡す方法
- ボタンを使って Tkinter ウィンドウを閉じる
- Tkinter ボタンの状態を変更する方法
- Tkinter のボタンをクリックして新しいウィンドウを作成する方法
- 複数のコマンドを Tkinter ボタンにバインドする方法
- Tkinter ボタンのサイズを変更する方法