- Tkinter GUI Application Development Cookbook
- Alejandro Rodas de Paz
- 156字
- 2021-08-27 19:44:01
How to do it...
In the following example, we will associate a StringVar instance to our entry with the textvariable option; this variable traces write operations with the show_message() method as callback:
import tkinter as tk class App(tk.Tk): def __init__(self): super().__init__() self.var = tk.StringVar() self.var.trace("w", self.show_message) self.entry = tk.Entry(self, textvariable=self.var) self.btn = tk.Button(self, text="Clear", command=lambda: self.var.set("")) self.label = tk.Label(self) self.entry.pack() self.btn.pack() self.label.pack() def show_message(self, *args): value = self.var.get() text = "Hello, {}!".format(value) if value else "" self.label.config(text=text) if __name__ == "__main__": app = App() app.mainloop()
When you type something into the Entry widget, the label updates its text with a message composed with the Tk variable value. For instance, if you type the word Phara, the label will show Hello, Phara!. If the entry is empty, the label will not show any text. To show you how to modify the variable's content programmatically, we added a button that clears the entry when you click on it:

推薦閱讀
- Java多線程編程實戰指南:設計模式篇(第2版)
- Python科學計算(第2版)
- Mastering Concurrency in Go
- Java高手真經(高級編程卷):Java Web高級開發技術
- PowerCLI Cookbook
- 人臉識別原理及算法:動態人臉識別系統研究
- Full-Stack Vue.js 2 and Laravel 5
- Python Data Analysis(Second Edition)
- Learning Three.js:The JavaScript 3D Library for WebGL
- Android開發案例教程與項目實戰(在線實驗+在線自測)
- Java程序設計入門
- Go語言編程
- 分布式數據庫原理、架構與實踐
- Distributed Computing in Java 9
- Modernizing Legacy Applications in PHP