官术网_书友最值得收藏!

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:

主站蜘蛛池模板: 沈阳市| 黎城县| 綦江县| 牙克石市| 安西县| 同心县| 平遥县| 泽库县| 宜州市| 钟山县| 明星| 麻江县| 辽阳市| 广宁县| 唐海县| 汉源县| 阿拉善盟| 丹巴县| 阿克陶县| 同江市| 汕头市| 武功县| 克什克腾旗| 建始县| 蓬溪县| 南城县| 井陉县| 藁城市| 巴林右旗| 宁武县| 大安市| 沧州市| 手游| 庆安县| 秀山| 海原县| 咸阳市| 长沙县| 淮安市| 徐水县| 南丰县|