简体   繁体   中英

Print variable value in Python Tkinter Label

I want to print a n_clusters_ variable in a label, but it's not updating. The computation of n_clusters_ is in another class. But I already set it as global variable. This is the code:

class nCluster():
    def __init__(self):
        label = Label(LabelHasil, text="Jumlah cluster yang ditemukan : ")
        label.pack(side=LEFT, padx=5, pady=5)
    def n_cluster(self):
        cluster_label = Label(LabelHasil, textvariable=n_clusters_)
        cluster_label.pack(side=LEFT, padx=5, pady=5)
show_n_cluster = nCluster()

This is the class where n_clusters_ is computed:

class Proses:
    def __init__(self):
        button = Button(window, text="Proses", command=lambda: stdbscan(self), width=10)
        button.pack()
    def stdbscan(self):
         ...
        global n_clusters_
        n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0) 
show_proses = Proses()

I need to print n_clusters_ variable whenever it's updated. Is it possible?

you define nCluster.n_cluster which should create and pack your label, but never call it. This doesn't actually need to be in its own method, either, just toss it in at the end of nCluster.__init__ .

The big problem is you need to make n_clusters_ a tkinter.StringVar so that it updates properly.

class Proses:
     ...
    def stdbscan(self):
     ...
    global n_clusters_
    n_clusters_ = StringVar()
    n_clusters_.set( len(set(labels)) - (1 if -1 in labels else 0) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM