rey rey - 3 months ago 21
Python Question

Dynamically printing value of entry in another entry

My code:

import tkinter as tk
disp = tk.Tk()
hlabel=tk.Label(text="host")
hlabel.grid(column=0,row=0)

host_entry = tk.Entry(disp)
host_entry.grid(row=0,column=1)

plabel=tk.Label(text="port")
plabel.grid(column=0,row=1)

port_entry = tk.Entry(disp)
port_entry.grid(row=1,column=1)

ulabel=tk.Label(text="Url")
ulabel.grid(column=0,row=3)
url_entry=tk.Entry(disp)
url_entry.grid(row=3,column=1)
url_entry.insert(0,'http://{0}:{1}'.format(host_entry.get(),port_entry.get()))
url_entry.config(state='disabled')
disp.mainloop()


I looked through this awesome answer but couldn't figure out.
The
'host'
and
'port'
should be displayed in the
'url'
Entry as
http://localhost:8080.
The text should be displayed dynamically in
url
.

Thanks for your help.

Answer

The simplest solution is to use a textvariable for each entry, put a trace on each variable, and then update the third entry whenever the trace fires.

First, define a function to update the third entry. It will be called by the trace functions, which automatically appends some arguments which we won't use:

def update_url(*args):
    host = host_var.get()
    port = port_var.get()
    url = "http://{0}:{1}".format(host, port)
    url_var.set(url)

Next, create the variables:

host_var = tk.StringVar()
port_var = tk.StringVar()
url_var  = tk.StringVar()

Next, add a trace on the host and port:

host_var.trace("w", update_url)
port_var.trace("w", update_url)

Finally, associate the variables with the entries:

host_entry = tk.Entry(..., textvariable=host_var)
port_entry = tk.Entry(..., textvariable=port_var)
url_entry=tk.Entry(..., textvariable=url_var)

Here it is as a full working example:

import tkinter as tk

def update_url(*args):
    host = host_var.get()
    port = port_var.get()
    url = "http://{0}:{1}".format(host, port)
    url_var.set(url)

disp = tk.Tk()

host_var = tk.StringVar()
port_var = tk.StringVar()
url_var  = tk.StringVar()

host_var.trace("w", update_url)
port_var.trace("w", update_url)

hlabel=tk.Label(text="host")
plabel=tk.Label(text="port")
ulabel=tk.Label(text="Url")
host_entry = tk.Entry(disp, textvariable=host_var)
port_entry = tk.Entry(disp, textvariable=port_var)
url_entry=tk.Entry(disp, textvariable=url_var)
url_entry.config(state='disabled')

hlabel.grid(column=0,row=0)
host_entry.grid(row=0,column=1)
plabel.grid(column=0,row=1)
port_entry.grid(row=1,column=1)
ulabel.grid(column=0,row=3)
url_entry.grid(row=3,column=1)

disp.mainloop()
Comments