[Tutor] Python Imported Code
Alan Gauld
alan.gauld at yahoo.co.uk
Tue Jun 25 13:17:31 EDT 2019
On 25/06/2019 14:50, stephen.m.smith at comcast.net wrote:
> using global, but that fails. I also can't seem to use arguments because the
> module that tkinter fires up with this command:
>
> self.process_button = tk.Button(master, text='Process Request', \
> font = ('times', regular_font,
> 'bold'),\
> fg = "blue",
> command=self.Process_Reservation_Request)
>
> does not seem to support the presence of arguments.
There is a common trick to get round that:
self.process_button = tk.Button(master,
text='Process Request',
font = ('times', regular_font,'bold'),
fg = "blue",
command=lambda :self.Process_Reservation_Request(x,y)
)
The lambda defines a function that takes no arguments but
which then calls your function with arguments.
Of course x and y need to be visible within the function
defining the lambda.
> Demo Program - This currently bombs in part 3 - it can't seem to see the
> value/space created in part1. Any help or reference that will clearly show
> Part 1
>
> import nice
> import nice2
> global myGlobal
> myGlobal = "initial value"
global here does nothing. global is only useful inside a function.
Remember that global in Python means module level - it does not
mean visible between modules!
> print(myGlobal)
> nice.changeGlobal()
> print (nice.myGlobal)
> nice2.changeGlobal()
>
> print("nice version = ", nice.myGlobal)
> print("nice2 version = ", nice2.myGlobal)
> print("mainline=", myGlobal)
>
> part 2 - stored as nice.py
>
> def changeGlobal():
> global myGlobal
This tells changeGlobal() that there is a variable called myGlobal
defined at the module level. That is, within nice. It does not
refer to the one you defined in Part 1.
> #print("entering changeGlobal part 1", myGlobal)
> myGlobal = "hello"
This now creates that module level variable with the value 'hello'.
> print("top of myGlobal", myGlobal)
>
> myGlobal="bye"
And this redefines nice.myGlobal to be 'bye'
The final value will now be seen by Part 1 code as
nice.myGlobal with a value of 'bye'.
> Part3 stored as nice2
> myGlobal = "hello"
This creates a new global variable called myGlobal within
the nice2 module. It is visible to Part 1 as nice2.myGlobal
> def changeGlobal():
> global myGlobal
This tells changeGlobal() to use the module level variable
above. ie nice2.myGlobal.
> print("first value = ", nice.myGlobal)
You didn't import nice into nice2 so this should give an error.
> myGlobal="it worked"
> print("in changeGlobal2 =", myGlobal)
This should set the variable nice2.myGlobal to 'it worked'
and that will be seen in Part 1 code as nice2.myGlobal.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list