0

This question made me wonder, what is exactly going on in the code below?

import tkinter as tk


class MyDot():
    def __str__(self):
        return "."


if __name__ == '__main__':
    root = tk.Tk()
    my_dot = MyDot()
    tk.Entry(root, textvariable=root).pack()
    tk.Label(root, textvariable=my_dot).pack()
    tk.Button(root, textvariable=".").pack()
    root.mainloop()

Why is having identical str(object)s, as textvariable option to widgets make their texts synchronized?

Nae
  • 14,209
  • 7
  • 52
  • 79
  • Wouldn't it be a bit scary if they *didn't* share the same content? – Peter Lewerin Jan 20 '18 at 12:08
  • @PeterLewerin Well, I updated the mcve to better reflect my surprize. – Nae Jan 20 '18 at 12:37
  • The widgets are guaranteed to have the same contents as the variable, and they share the same variable. How could they have different contents? – Peter Lewerin Jan 20 '18 at 15:03
  • @PeterLewerin They don't share the _same variable_ per se as far as python is concerned. They just happen to have the same _string_, which is apparently the same variable in _Tcl_. – Nae Jan 20 '18 at 15:21
  • 2
    Now I see your confusion, I think. Python apparently delegates all or most of what Tk does to a Tcl interpreter, so the string becomes the name of a variable that lives in that interpreter's memory but is invisible and unreachable from Python. (In Tcl/Tk it is common practice to synchronize widgets this way.) On the Python side, this interaction is of course less obvious as the variable doesn't exist as a Python variable. Sorry for misunderstanding your question. – Peter Lewerin Jan 20 '18 at 16:39

0 Answers0