The set
method only uses the old string formatting method using %
to assign the string to be displayed by the Label
, which follows the syntax:
% values format
where formato
is the string to be formatted, which contains one or more specifiers to be replaced that are identified by the character "%"
at the beginning of it, while valores
can be a single element or a tuple of items with the same number of items specified in the format or a mapping object, such as a dictionary.
You can see a much more detailed explanation in the documentation:
Some examples:
>>> "Un rectángulo de %.2f cm de ancho por %.2f cm de alto" % (4.2555, 8.2146)
'Un rectángulo de 4.26 cm de ancho por 8.21 cm de alto'
>>> "Stack Overlow en %s" % "español"
'Stack Overlow en español'
>>> '%(nombre)s tiene %(edad)d años' % {"nombre": "Pedro", "edad": 27}
'Pedro tiene 27 años'
Currently this method is still available but is considered outdated in favor of str.format
and the formatted string literals (Python > = 3.6) both considerably more flexible.
You also have an extensive explanation with examples included in the documentation:
In your case the method expects a string to be formatted as the first argument and an indeterminate number of positional arguments that will correspond exactly to the values to be replaced in the string. A reproducible example so you can see it with some different examples of method call:
import tkinter as tk
class StatusBar(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.label = tk.Label(self, bd=1, relief=tk.SUNKEN, anchor=tk.W)
self.label.pack(fill=tk.X)
def set_string(self, format_, *args):
self.label.config(text=format_ % args)
self.label.update_idletasks()
def clear(self):
self.label.config(text="")
self.label.update_idletasks()
if __name__ == "__main__":
root = tk.Tk()
root.geometry("400x200")
f1 = StatusBar(root)
f1.set_string("%.2f, %.2f", 4.257, 2.356)
f1.pack(fill=tk.X)
f2 = StatusBar(root)
f2.set_string("%s, %s y %s", "Pedro", "Laura", "Marco")
f2.pack(fill=tk.X)
f3 = StatusBar(root)
f3.set_string("%30s", "Stack Overflow")
f3.pack(fill=tk.X)
f4 = StatusBar(root)
a = 2
b = 3
r = 6
op = "x"
f4.set_string("%d %s %d = %d", a, op, b, r)
f4.pack(fill=tk.X)
root.mainloop()
Note: Avoid using set
and format
as names for our methods or variables, both functions are prebuilt in Python, which overlap with it, apart from being confusing .
*args
is used to send an indeterminate number of arguments ("non-keywords") to the function, so that at the end args
will be a tuple that will contain the values of those arguments and whose length is only known at run time when the function is called. This is so, because the number of arguments of the function depends on the number of specifiers to be substituted in the chain passed as the first argument, as seen in the previous example.