{"id":22025,"date":"2021-09-25T11:56:45","date_gmt":"2021-09-25T11:56:45","guid":{"rendered":"https:\/\/www.askpython.com\/?p=22025"},"modified":"2021-10-01T20:32:43","modified_gmt":"2021-10-01T20:32:43","slug":"stringvar-with-examples","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python-modules\/tkinter\/stringvar-with-examples","title":{"rendered":"Tkinter StringVar with Examples &#8211; Tkinter Tutorial"},"content":{"rendered":"\n<p>Hello folks! In this tutorial, we will look at how to use StringVar function in Tkinter as a way to store text variables and to edit text in widgets. We will also see an example to write callbacks to notify when there is a change in the text variable. So let&#8217;s get started.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What is StringVar()?<\/h2>\n\n\n\n<p>Tkinter contains build-in programming types which work like a normal python variable with additional features used to manipulate values of widgets like <code>Label<\/code> and <code>Entry<\/code> more effectively, which makes them different from python data types. These variables also contain getter and setter methods to access and change their values. <code>StringVar<\/code> is an example of them.<\/p>\n\n\n\n<p>A variable defined using <code>StringVar()<\/code> holds a string data where we can set text value and can retrieve it. Also, we can pass this variable to textvariable parameter for a widget like Entry. The widget will automatically get updated with the new value whenever the value of the <code>StringVar()<\/code> variable changes.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Defining a StringVar() variable<\/h2>\n\n\n\n<p>Here is what it takes to define a string variable using Tkinter <code>StringVar()<\/code>:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>master<\/strong>: It is a widget that the <code>StringVar<\/code> object is associated with. If nothing is specified, it defaults to the root window.<\/li><li><strong>value<\/strong>: The initial value given to the string variable. Defaults to &#8220;&#8221;.<\/li><li><strong>name<\/strong>: The name given to the defined variable. Default value is PY_VARnum(like PY_VAR1, PY_VAR2, etc).<\/li><\/ul>\n\n\n\n<p>For example, in the code below, we create a string variable using <code>StringVar()<\/code> and assign it to the textvariable parameter of <code>Label<\/code> widget.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport tkinter as tk\n\nmaster_window = tk.Tk()\nmaster_window.geometry(&quot;150x150&quot;)\nmaster_window.title(&quot;StringVar Example&quot;)\n\nstring_variable = tk.StringVar(master_window, &quot;Hello Everyone!!&quot;)\n\nlabel = tk.Label(master_window, textvariable=string_variable, height=150)\nlabel.pack()\n\nmaster_window.mainloop()\n<\/pre><\/div>\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full is-resized\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2021\/09\/Defining-StringVar.jpg\" alt=\"Defining StringVar\" class=\"wp-image-22083\" width=\"254\" height=\"278\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2021\/09\/Defining-StringVar.jpg 385w, https:\/\/www.askpython.com\/wp-content\/uploads\/2021\/09\/Defining-StringVar-274x300.jpg 274w\" sizes=\"auto, (max-width: 254px) 100vw, 254px\" \/><figcaption>Defining StringVar<\/figcaption><\/figure><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Setting values of StringVar() variables<\/h2>\n\n\n\n<p>Values can be assigned to string variables defined using <code>StringVar()<\/code> using 2 ways:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>Passing the value in constructor<\/strong>: You can pass the value of the string variable in <code>value<\/code> parameter of the constructor while defining the Tkinter variable.<\/li><\/ul>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nstring_variable = tk.StringVar(master=master_window, value=&quot;Initial value of string variable&quot;)\n<\/pre><\/div>\n\n\n<ul class=\"wp-block-list\"><li><strong>Using the <code>set()<\/code> method<\/strong>: You can use <code>set()<\/code> method to change the value of the string. For example:<\/li><\/ul>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nstring_variable = tk.StringVar(master_window)\nstring_variable.set(&quot;Some Text&quot;)\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">Retrieving values of StringVar() variables<\/h2>\n\n\n\n<p>We can use <code>get()<\/code> method on <code>StringVar()<\/code> variable to retrieve the text value present in the variable.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; highlight: [8]; title: ; notranslate\" title=\"\">\nimport tkinter as tk\n\nmaster_window = tk.Tk()\n\nstring_variable = tk.StringVar(master_window)\nstring_variable.set(&quot;Welcome to AskPython!!&quot;)\n\nprint(string_variable.get())\n<\/pre><\/div>\n\n\n<p>Using this way, we can also retrieve the data present in the <code>Entry<\/code> widget when StringVar variable is passed to the widget. For example:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; highlight: [8]; title: ; notranslate\" title=\"\">\nimport tkinter as tk\n\nmaster_window = tk.Tk()\nmaster_window.geometry(&quot;300x300&quot;)\nmaster_window.title(&quot;StringVar get() example&quot;)\n\ndef print_data():\n    print(string_variable.get())\n\nstring_variable = tk.StringVar(master_window)\n\nlabel = tk.Label(master_window, text=&quot;Enter Data: &quot;)\nlabel.grid(row=0, column=0)\n\nentry = tk.Entry(master_window, textvariable=string_variable)\nentry.grid(row=0, column=1)\n\nbutton = tk.Button(master_window, text=&quot;Print data&quot;, command=print_data)\nbutton.grid(row=1, column=0, columnspan=2)\n\nmaster_window.mainloop()\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">Writing callbacks to trace the StringVar() variables<\/h2>\n\n\n\n<p>One interesting feature of Tkinter-defined objects is that the object will be notified whenever its value is changed, read, or deleted. This feature is helpful if you want to update other widgets automatically in case of some operation on Tkinter-defined objects.<\/p>\n\n\n\n<p>To define a callback on <code>StringVar()<\/code> object, we can use <code>trace()<\/code> method on the <code>StringVar()<\/code> object that takes 2 parameters:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>mode: The type of operation on the <code>StringVar()<\/code> object. <ul><li><code>'w'<\/code> (write): invoke callback when value is changed<\/li><li><code>'r'<\/code> (read): invoke callback when value is read<\/li><li><code>'u'<\/code> (unset): invoke callback when value is deleted<\/li><\/ul><\/li><li>callback: method to call when there is an operation on the object.<\/li><\/ul>\n\n\n\n<p>Let&#8217;s consider an example where a greeting message will be generated for the name entered in the <code>Entry<\/code> widget. As we change the data in the <code>StringVar()<\/code> object through <code>Entry<\/code> widget, a method will be called that will change the greeting message simultaneously.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; highlight: [9,10]; title: ; notranslate\" title=\"\">\nimport tkinter as tk\n\nclass GreetingApp(tk.Tk):\n    def __init__(self):\n        super().__init__()\n        self.title(&#039;Greeting Application&#039;)\n        self.geometry(&quot;300x300&quot;)\n\n        self.name_var = tk.StringVar()\n        self.name_var.trace(&#039;w&#039;, self.create_greeting_message)\n\n        self.create_widgets()\n    \n    def create_widgets(self):\n        self.description_label = tk.Label(self, text=&quot;Enter your name:&quot;)\n        self.description_label.grid(column=0, row=0)\n\n        self.entry = tk.Entry(self, textvariable=self.name_var)\n        self.entry.grid(column=1, row=0)\n        self.entry.focus()\n\n        self.greeting_label = tk.Label(self)\n        self.greeting_label.grid(column=0, row=1, columnspan=2)\n    \n    def create_greeting_message(self, *args):\n        name_entered = self.name_var.get()\n\n        greeting_message = &quot;&quot;\n        if name_entered != &quot;&quot;:\n            greeting_message = &quot;Hello &quot; + name_entered\n        \n        self.greeting_label&#x5B;&#039;text&#039;] = greeting_message\n\nif __name__ == &quot;__main__&quot;:\n    app = GreetingApp()\n    app.mainloop()\n<\/pre><\/div>\n\n\n<p>Here is the result:<\/p>\n\n\n\n<figure class=\"wp-block-video aligncenter\"><video height=\"864\" style=\"aspect-ratio: 1536 \/ 864;\" width=\"1536\" controls src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2021\/09\/Stringvar-Greeting-Example.webm\"><\/video><figcaption>StringVar() Greeting Example<\/figcaption><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>In this tutorial, we learned about <code>StringVar()<\/code> in Tkinter and how to use it to set the string value, retrieve it and writing callbacks that automatically changes the data.<\/p>\n\n\n\n<p>Thanks for reading!!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hello folks! In this tutorial, we will look at how to use StringVar function in Tkinter as a way to store text variables and to edit text in widgets. We will also see an example to write callbacks to notify when there is a change in the text variable. So let&#8217;s get started. What is [&hellip;]<\/p>\n","protected":false},"author":31,"featured_media":22270,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[92],"tags":[],"class_list":["post-22025","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-tkinter"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/22025","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/31"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=22025"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/22025\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/22270"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=22025"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=22025"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=22025"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}