K
K
Konstantin Ermolaev2021-07-14 11:26:12
Python
Konstantin Ermolaev, 2021-07-14 11:26:12

How to use a variable from a function inside a class to work with other functions?

Hello, I'm asking you this question...

There is a class "Table" , it has a function "CopyTextToClipboard" , this function has a variable "id_num" . The variable is categorically important for further work outside the class and its native function. The task is to correctly pass this variable 1) to the function (of the "Win_status()" child window ) 2) simply to the code (for the label). The code is actually below:
Class

class Table(tk.Frame):
    def __init__(self, parent=None, headings=tuple(), rows=tuple()):
        super().__init__(parent)
        
        table = ttk.Treeview(self, show="headings", selectmode="browse")
        table["columns"] = headings
        table["displaycolumns"] = headings
  
        for head in headings:
            table.heading(head, text=head, anchor=tk.CENTER)
            table.column(head, anchor=tk.CENTER, width=20)
  
        for row in rows:
            table.insert('', tk.END, values=tuple(row))
        
        table.bind("<ButtonRelease-1>", lambda event, tree = table: self.CopyTextToClipboard(event, tree))
  
        scrolltable = tk.Scrollbar(self, command=table.yview)
        scrolltable1 = tk.Scrollbar(self, command= table.xview)
        table.configure(yscrollcommand=scrolltable.set)
        table.configure(xscrollcommand=scrolltable1.set)
        scrolltable.pack(side=tk.RIGHT, fill=tk.Y)
        scrolltable1.pack(side=tk.BOTTOM, fill=tk.X)
        table.pack(expand=tk.YES, fill=tk.BOTH)

    def CopyTextToClipboard (self, event, tree):
        global id_num
        id_num = tree.item(tree.focus())['values'][0]
        print(id_num)


Function (in which you need to use a variable):
def Win_status ():
    #id_num = Table.CopyTextToClipboard.id_num()
    ws = tk.Toplevel(mwin)
    ws.title('Окно осмотра ТС')
    ws.geometry ('300x650')
    ws.resizable(0,0)
    spec_written = StringVar()
    spec_lbl1 = tk.Label(ws, text='По заявке', fg= 'Black', font='Arial 12 bold')
    spec_lbl1.place(x= 10, y = 10)
    spec_lbl2 = tk.Label(ws,text = id_num, fg= 'Green', font='Complex 12 bold')
    spec_lbl2.place(x= 120, y = 10)
    spec_lbl3 = tk.Label(ws,text='В ходе диагностического осмотра ', fg= 'Black', font='Arial 10')
    spec_lbl3.place(x= 50, y = 35)
    spec_lbl4 = tk.Label(ws,text='были установлены следующие неисправности:', fg= 'Black', font='Arial 10')
    spec_lbl4.place(x= 10, y = 60)
    t_b_desk = tk.Text(ws, width =34, height = 8, bg = 'black', fg = 'white')
    t_b_desk.place(x=10, y= 100)  
    spec_lbl5 = tk.Label(ws,text='ТС установлен статус:', fg= 'Black', font='Arial 10')
    spec_lbl5.place(x= 70, y = 250)
    spec_com = ttk.Combobox(ws, width=32, height=4, font= 'Arial 11', values= ['Обслуживается -- не требует зпч',
                                                                               'Обслуживается -- требует зпч', 
                                                                                'Отложен с правом выезда',
                                                                                'Отложен без права выезда'
                                                                                ])
    spec_com.place(x=10, y=280 )
    cpec_bt = tk.Button(ws, text='Дополнить заявку', bg= 'Green', fg= 'White', width=50)
    cpec_bt.pack(side= tk.BOTTOM, fill= tk.BOTH, pady=10, padx=5)
    spec_lbl6 = tk.Label(ws, text='специалистами АРМ \n проведены следующие работы:', font= 'Arial 10')
    spec_lbl6.place(x= 50, y= 320)
    spec_text = tk.Text (ws, width=34, height= 8, bg= 'black', fg= 'white')
    spec_text.place(x= 10, y= 380)
    spec_lbl7 = tk.Label(ws, text='Ответственный специалист:', font= 'Arial 12 bold')
    spec_lbl7.place(x= 20, y= 520)
    spec_entr = tk.Entry(ws,  textvariable= spec_written, width = 33,  font = ('Arial',  '11', 'bold')) 
    spec_entr.place(x=10 , y= 550)


Well, the label in the code itself, which also needs this variable:
fra_s = tk.Frame(mwin, width=200, height=30, bg= '#708090')
fra_s.place(x=1250,y=20)
lbl_num = Label(fra_s, text= id_num, fg= 'Green', font='Arial 12 bold' ).pack()


P/S.
I confidently guess that this is somewhat contrary to the principles of OOP and the usual return does not do this. But, as I understand it, it can be done - and I just need it.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Artem Imaev, 2021-07-14
@AIRC24

I think you want to use the variable in other functions. you need to make it global, you need to call it outside the function, then in the function assign global "variable name"

d = 12
def de():
    global d
    d-=2
    print(d)
de()

R
res2001, 2021-07-14
@res2001

You already have this variable declared global in CopyTextToClipboard global id_num. Make the same declaration in all necessary places and use. And declare this variable explicitly in the global scope.

this is somewhat contrary to the principles of OOP

Not really. We need more information about the architecture of the application to draw such conclusions.
Instead of a global variable, you can return a value from a function, or make this variable a member of the class and make a getter to get the value of the variable, etc. etc. But no one can choose the right option for you.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question