简体   繁体   中英

How to change global variable using other file by importing

I have made this calculator on Python with GUI using Tkinter , it's my university project but there are some requirements and one is that every function should be imported in the main GUI file not to be placed there.

For example, I have created a null operator textinput for textvariable and buttons from 1 to 9 and defined a button click handler function for it:

def btnClick(numbers):
    global operator
    operator=operator+str(numbers)
    text_Input.set(operator)

And I have saved this in the other file called "Buttons.py"

Now when i call it in my gui file like this and make a button to execute it

import Buttons
button7=Button(cal,padx=16,bd=4,fg='black',font=('The Citadels',20),
           text='7',command=lambda:Buttons.btnClick(7),bg='ghost white')
    .grid(row=5,column=0)

But get an error saying

name 'operator' is not defined

What is missing for my code to work ?

When you use the import statement on its own, you import the module but you don't import the namespace. operators is not defined because it is part of the module's namespace. To fix this, you can either use Buttons.operator instead of operator , or you can change your import statement to look like from Buttons import * , which will import all the variables from Buttons into your namespace as well.

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