473,662 Members | 2,724 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Managing events

Hi,

I have a class (a gui) with buttons and other controls. A button, for
example, has a callback method, so that writing

b = Button(label, OnClick)

will call the global OnClick method.

Now, if I want the OnClick method to call some of my main class methods,
I need to write:

UI = None
...
class MainClass:
...
global UI = self
Then,
def OnClik(button):
UI.do_something (button.get_lab el())

Is this the correct way to do it in Python ? Isn't there a potential
flaw in declaring my MainClass instance as a global variable ?
Sep 3 '05 #1
4 1218
cantabile wrote:
Hi,

I have a class (a gui) with buttons and other controls. A button, for
example, has a callback method, so that writing

b = Button(label, OnClick)

will call the global OnClick method.

Now, if I want the OnClick method to call some of my main class methods,
I need to write:

UI = None
...
class MainClass:
...
global UI = self
Then,
def OnClik(button):
UI.do_something (button.get_lab el())

Is this the correct way to do it in Python ? Isn't there a potential
flaw in declaring my MainClass instance as a global variable ?


Yes. Normally graphical widgets are declared as object classes (in both
wxPython and Tkinter, at least) for precisely this reason.

Then the onClick() can be a method of the class, and the callback is a
bound method of the class (in other words a method that's already
identified with a specific instance).

Here's a simple-ish piece of wxPython code to demonstrate. Notice that
each paramDialog closes its own dialog box, because the callback
provided in the event binding is already bound to the instance.

import wx

class paramDialog(wx. Dialog):
count = 0 # Class variable counts # of instances
def __init__(self, parent):
wx.Dialog.__ini t__(self, parent, id=-1, title="This is a
Dialog", size=(300, 250))
btn = wx.Button(self, -1, "Close Me", (100, 75))
# THIS LINE ASSOCIATES A BOUND METHOD OF THE CURRENT
# INSTANCE WITH A CLICK ON THE "Close Me" BUTTON OF
# THIS PARTICULAR DIALOG INSTANCE
btn.Bind(wx.EVT _BUTTON, self.shutdown)
self.Bind(wx.EV T_CLOSE, self.shutdown)
self.SetAutoLay out(True)
paramDialog.cou nt += 1

def shutdown(self, evt):
paramDialog.cou nt -= 1
self.Destroy()
if paramDialog.cou nt == 0:
app.Destroy()
import sys
sys.exit("Done" )
class MyApp(wx.App):
# wxWidgets calls this method to initialize the application
def OnInit(self):
frame = wx.Frame(None, -1, "This is the main frame")
self.SetTopWind ow(frame)
d1 = paramDialog(fra me)
d2 = paramDialog(fra me)
d3 = paramDialog(fra me)
d1.Show()
d2.Show()
d3.Show()
return True

if __name__ == '__main__':
app = MyApp(0)
app.MainLoop()

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

Sep 3 '05 #2
cantabile wrote in news:43******** **************@ news.wanadoo.fr in
comp.lang.pytho n:
Hi,

I have a class (a gui) with buttons and other controls. A button, for
example, has a callback method, so that writing

b = Button(label, OnClick)

will call the global OnClick method.

Now, if I want the OnClick method to call some of my main class
methods,
I need to write:

UI = None
...
class MainClass:
...
global UI = self
Then,
def OnClik(button):
UI.do_something (button.get_lab el())

Is this the correct way to do it in Python ?


Try:

class MainClass:
def do_something( self, label ):
pass

def OnClick( self, button ):
self.do_somethi ng( button.get_labe l() )

def some_method( self ):
b = Button( label, self.OnClick )
With the above you could also do:

main = MainClass()
b = Button( "A Label", main.OnClick )

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Sep 3 '05 #3
On Sat, 03 Sep 2005 19:03:33 +0200, cantabile <ca**********@w anadoo.fr>
declaimed the following in comp.lang.pytho n:

No solution, just more questions...
Hi,

I have a class (a gui) with buttons and other controls. A button, for
example, has a callback method, so that writing

b = Button(label, OnClick)

will call the global OnClick method.
Why is "OnClick" a global? Or maybe I just didn't understand your
usage... Do you have just ONE OnClick being used by multiple buttons, or
does each button have its own OnClick?

Second question: what GUI framework? Tkinter, or something else?
Might affect the answer..

As I recall, this is one of those places where Tkinter would suggest
use of a lambda expression to delay function calling so an argument
specific to the button can be supplied... My book is at work, so I can't
do up an example...
-- =============== =============== =============== =============== == <
wl*****@ix.netc om.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
=============== =============== =============== =============== == <
Home Page: <http://www.dm.net/~wulfraed/> <
Overflow Page: <http://wlfraed.home.ne tcom.com/> <

Sep 3 '05 #4
Thanks to you all for these answers. I'll try these ideas and post back
comments and results.
Sep 4 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1981
by: thechaosengine | last post by:
Hi all, Does anyone know of a design pattern to deal with the issue of making UI controls active and inactive according to the context of what the user is doing? I've been thinking about the best way to handle this but the only way I can really think to do it would likely be very messy - trying to deal with it in event handlers. I can imagine that trying to disable and enable buttons and menu items and toolbars for a whole host of ui...
3
1507
by: Torsten Wiebesiek | last post by:
Hi, I am currently working on a computer vision system. At the moment I'm adding support for firewire cameras. Since there is only one firewire system on a computer, I have writen a firewire manager class as Singleton. User access to firewire camera objects should only be accessable via refereces obtained from this manager class. I want to avoid the creation of more than one camera object accessing the same physical camera.
7
3612
by: tgh003 | last post by:
I would be interested to hear how others are managing their javascript (.js) files from the original code vs the obfuscated version they publish to their site/webapp. I currently manage 2 files, and everytime i need to make a change, I have to switch the names, test, then rename again, obfuscate to the original file name (because this is the file referenced in php/perl/asp whatever files). So its kind of a pain. Any thoughts out...
14
1814
by: RL Stevenson | last post by:
What is a reasonable way to manage a complex form with 5 or so tabs with 100 or more controls bound to 5-10 tables in a database? Pasting all those controls, datasets, data adapters directly onto the form resulted in an unwieldy file of nearly 10,000 lines of code. Seems like there must be a better way.
0
1020
by: deepak | last post by:
y objective is to retrieve data from a remote server through sockets.the Maximum no of sockets that can be opened are four. The component that has to be developed in .net which must be COM compatible. I would like to utilize asynchronous programming model of sockets in receiving data. my basic idea on how to start was like this define a connection class called connection that has a static member called socket. so there will be only one...
0
928
by: batista | last post by:
Hello all, Let me first explain my windows application.... I have a grid which is bound to a dataview of a dataset... Now this dataset is updated from a separate thread and therefore I've used a Custom class which is inherited by dataview...and the OnListChanged and IndexListChanged event are overridden...and in those funtions im using begininvoke to make sure that when dataset changes from separate thread the grid does'nt...
1
2067
by: AJ | last post by:
Hi all, Just throwing something out to the newsgroup to get a feel for what others are doing. I am noticing that with my current coding practice, every time i want to update a database i generally implement the following pattern. 1) Open db connnection 2) Execute Query
2
1740
by: fariba123 | last post by:
i have designed an employee information site. there is an option to generate pay slip. how can i show the employee related data based on the drop down list. i have found code example for managing list boxes. but i need help on managing multiple text boxes. please give a quick reaply. thank you
6
1301
by: kirk | last post by:
I have three events, using event handler methods as depicted below. Two of those event handler methods need to reset specific data whenever the other event left fires. I wasn't sure how to properly implement that, is there a better way than using state management variables for each timer as i'm doing in the outline below? private string szProperty1 = null; // updated by class consumer
2
1032
by: Justin | last post by:
I've never work with creating controls on the fly. Now that I am, I'm uncertain about a particular aspect. Example: I have a static listbox named ListBox1. I use the following routine: Private Sub ListBox1_MouseDown(........) Handles ListBox1.MouseDown That's great for ListBox1 however how do I handle a listbox I create and
0
8857
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8768
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8547
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8633
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7368
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6186
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4181
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2763
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1754
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.