Retrieve Combobox Name in Tkinter From Bind Event - python-3.x
I am trying to create a settings window in tkinter python, I am trying to create same callback function for all comboboxes, but I can't figure how to identify which combobox is the caller. example code:
def Open_settings_Form():
def callbackFunc(event):
print(event.widget.current())
global SETTINGS
Settings_Form = Toplevel(Main_Form)
Settings_Form.title("LOG Settings")
Settings_Form.geometry('900x300')
labelTop = Label(Settings_Form, text = "Log Parsing Order")
labelTop.grid(column=0, row=0)
combo0 = ttk.Combobox(Settings_Form, state="readonly", values=Log_Fields)
combo0.bind("<<ComboboxSelected>>", callbackFunc)
combo0.current(SETTINGS['LOG_Order'][0])
combo0.grid(column=0, row=1)
combo1 = ttk.Combobox(Settings_Form, state="readonly", values=Log_Fields)
combo1.bind("<<ComboboxSelected>>", callbackFunc)
combo1.current(SETTINGS['LOG_Order'][1])
combo1.grid(column=1, row=1)
combo2 = ttk.Combobox(Settings_Form, state="readonly", values=Log_Fields)
combo2.bind("<<ComboboxSelected>>", callbackFunc)
combo2.current(SETTINGS['LOG_Order'][2])
combo2.grid(column=2, row=1)
combo3 = ttk.Combobox(Settings_Form, state="readonly", values=Log_Fields)
combo3.bind("<<ComboboxSelected>>", callbackFunc)
combo3.current(SETTINGS['LOG_Order'][3])
combo3.grid(column=3, row=1)
In my callbackFunc I can get the selected item of combobox, but not able to find which combobox fire the event. Is there any other bind method than ComboboxSelected which I am using ?
Following are the methods / Params for event.widget object:
['_Misc__winfo_getint', '_Misc__winfo_parseitem', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_bind', '_configure', '_displayof', '_do', '_getboolean', '_getconfigure', '_getconfigure1', '_getdoubles', '_getints', '_grid_configure', '_gridconvvalue', '_last_child_ids', '_name', '_nametowidget', '_noarg_', '_options', '_register', '_report_exception', '_root', '_setup', '_subst_format', '_subst_format_str', '_substitute', '_tclCommands', '_w', '_windowingsystem', 'after', 'after_cancel', 'after_idle', 'anchor', 'bbox', 'bell', 'bind', 'bind_all', 'bind_class', 'bindtags', 'cget', 'children', 'clipboard_append', 'clipboard_clear', 'clipboard_get', 'columnconfigure', 'config', 'configure', 'current', 'delete', 'deletecommand', 'destroy', 'event_add', 'event_delete', 'event_generate', 'event_info', 'focus', 'focus_displayof', 'focus_force', 'focus_get', 'focus_lastfor', 'focus_set', 'forget', 'get', 'getboolean', 'getdouble', 'getint', 'getvar', 'grab_current', 'grab_release', 'grab_set', 'grab_set_global', 'grab_status', 'grid', 'grid_anchor', 'grid_bbox', 'grid_columnconfigure', 'grid_configure', 'grid_forget', 'grid_info', 'grid_location', 'grid_propagate', 'grid_remove', 'grid_rowconfigure', 'grid_size', 'grid_slaves', 'icursor', 'identify', 'image_names', 'image_types', 'index', 'info', 'insert', 'instate', 'keys', 'lift', 'location', 'lower', 'mainloop', 'master', 'nametowidget', 'option_add', 'option_clear', 'option_get', 'option_readfile', 'pack', 'pack_configure', 'pack_forget', 'pack_info', 'pack_propagate', 'pack_slaves', 'place', 'place_configure', 'place_forget', 'place_info', 'place_slaves', 'propagate', 'quit', 'register', 'rowconfigure', 'scan_dragto', 'scan_mark', 'select_adjust', 'select_clear', 'select_from', 'select_present', 'select_range', 'select_to', 'selection_adjust', 'selection_clear', 'selection_from', 'selection_get', 'selection_handle', 'selection_own', 'selection_own_get', 'selection_present', 'selection_range', 'selection_to', 'send', 'set', 'setvar', 'size', 'slaves', 'state', 'tk', 'tk_bisque', 'tk_focusFollowsMouse', 'tk_focusNext', 'tk_focusPrev', 'tk_setPalette', 'tk_strictMotif', 'tkraise', 'unbind', 'unbind_all', 'unbind_class', 'update', 'update_idletasks', 'validate', 'wait_variable', 'wait_visibility', 'wait_window', 'waitvar', 'widgetName', 'winfo_atom', 'winfo_atomname', 'winfo_cells', 'winfo_children', 'winfo_class', 'winfo_colormapfull', 'winfo_containing', 'winfo_depth', 'winfo_exists', 'winfo_fpixels', 'winfo_geometry', 'winfo_height', 'winfo_id', 'winfo_interps', 'winfo_ismapped', 'winfo_manager', 'winfo_name', 'winfo_parent', 'winfo_pathname', 'winfo_pixels', 'winfo_pointerx', 'winfo_pointerxy', 'winfo_pointery', 'winfo_reqheight', 'winfo_reqwidth', 'winfo_rgb', 'winfo_rootx', 'winfo_rooty', 'winfo_screen', 'winfo_screencells', 'winfo_screendepth', 'winfo_screenheight', 'winfo_screenmmheight', 'winfo_screenmmwidth', 'winfo_screenvisual', 'winfo_screenwidth', 'winfo_server', 'winfo_toplevel', 'winfo_viewable', 'winfo_visual', 'winfo_visualid', 'winfo_visualsavailable', 'winfo_vrootheight', 'winfo_vrootwidth', 'winfo_vrootx', 'winfo_vrooty', 'winfo_width', 'winfo_x', 'winfo_y', 'xview', 'xview_moveto', 'xview_scroll']
Thanks a lot
You can pass a name to your combobox widget and retrieve it through event.widget callback.
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
def details(event):
print (event.widget)
combo1 = ttk.Combobox(root,name="box1")
combo1["values"] = ("A","B","C")
combo1.pack()
combo1.bind("<<ComboboxSelected>>",details)
combo2 = ttk.Combobox(root,name="box2")
combo2["values"] = ("D","E","F")
combo2.pack()
combo2.bind("<<ComboboxSelected>>",details)
root.mainloop()
Related
Python get list of o365 users through MS Graph. Missing infomtion
from O365 import Account credentials = ('hidden', 'hidden') # the default protocol will be Microsoft Graph account = Account(credentials, auth_flow_type='credentials', tenant_id='hidden') users_list=[] directory = account.directory() for user in directory.get_users(): print(dir(user)) I am connected to O365 and can gather users. I would like to see the users last password change date but the class is returning a None type. is this a MS graph permissions error or is it now supported in this API. see the bellow result. ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_base_url', '_build_date_time_time_zone', '_cc', '_cloud_data_key', '_endpoints', '_gk', '_parse_date_time_time_zone', '_parse_resource', 'about_me', 'account_enabled', 'age_group', 'assigned_licenses', 'assigned_plans', 'birthday', 'build_base_url', 'build_url', 'business_phones', 'city', 'company_name', 'con', 'consent_provided_for_minor', 'country', 'created', 'department', 'display_name', 'employee_id', 'fax_number', 'full_name', 'get_profile_photo', 'given_name', 'hire_date', 'im_addresses', 'interests', 'is_resource_account', 'job_title', 'last_password_change', 'legal_age_group_classification', 'license_assignment_states', 'mail', 'mail_nickname', 'mailbox_settings', 'main_resource', 'message_constructor', 'mobile_phone', 'my_site', 'new_message', 'new_query', 'object_id', 'office_location', 'other_mails', 'password_policies', 'password_profile', 'past_projects', 'postal_code', 'preferred_data_location', 'preferred_language', 'preferred_name', 'protocol', 'provisioned_plans', 'proxy_addresses', 'q', 'responsibilities', 'schools', 'set_base_url', 'show_in_address_list', 'sign_in_sessions_valid_from', 'skills', 'state', 'street_address', 'surname', 'type', 'update_profile_photo', 'usage_location', 'user_principal_name', 'user_type']
Why the function 'os.open(file_path, flag)' returns an integer?
I know I can use the function 'os.open' to deal with '.txt' files. But nevertheless I tried to open a '.jpg' file using this function as shown in the code below: import os f1 = os.open('imagem.jpg', os.O_RDONLY) When I call f1 object to see what is inside it, python returns to me a integer that changes according to the number of times I have run the 'f1 = os.open('imagem.jpg', os.O_RDONLY)' code. For example, the first time I run 'f1 = os.open('imagem.jpg', os.O_RDONLY)', f1 will assume 1, second time, 2, so on... When I run the code below to see the methods and atributes of f1: dir(f1) python returns it to me: ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes'] Some one can explain to me what is happening?
datetime - a bug or a feature?
from datetime import datetime, timedelta now = datetime.now() then = datetime(2001, 1, 1) delta = now-then print(delta) print(delta.days, delta.seconds) print(delta.hours, delta.minutes) gives the following errors: 6959 days, 16:09:27.863408 6959 58167 AttributeError: 'datetime.timedelta' object has no attribute 'hours' AttributeError: 'datetime.timedelta' object has no attribute 'minutes' is it a bug or a feature?
A feature: timedelta objects only have .days, .seconds, and .microseconds. I suppose this is because days are sometimes irregular (e.g. due to leap seconds, and date arithmetic can account for that), while minutes and hours can be readily computed from seconds. Could have been slightly nicer, but still would have a few corner cases.
You can check all attributes in this way: >>> dir(delta) ['__abs__', '__add__', '__bool__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__pos__', '__radd__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rmod__', '__rmul__', '__rsub__', '__rtruediv__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', 'days', 'max', 'microseconds', 'min', 'resolution', 'seconds', 'total_seconds'] There are no "hours" and "minutes"
python: variables in a function with dot preceded by the function name
I need to understand this concept wherein we can use the dot (.) in the variable name within a function definition. There's no class definition nor a module here and Python is not supposed accept a variable name that includes a dot. def f(x): f.author = 'sunder' f.language = 'Python' print(x,f.author,f.language) f(5) `>>> 5 sunder Python` Please explain how this is possible, and suggest related documentation for further exploration.
From official documentation: Programmer’s note: Functions are first-class objects. A “def” statement executed inside a function definition defines a local function that can be returned or passed around. Free variables used in the nested function can access the local variables of the function containing the def. So, function is an object: >>> f.__class__ <class 'function'> >>> f.__class__.__mro__ (<class 'function'>, <class 'object'>) ... and it means that it can store attributes: >>> f.__dict__ {'language': 'Python', 'author': 'sunder'} >>> dir(f) ['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'author', 'language']
Python self keyword: advantages and drawbacks
What is the difference between these 2 classes (in terms of performance and design): class A: def methodA(self): self.a=10 print(self.a) And: class B: def methodB(self): b=10 print(b)
b in the second example is local variable, not class-instance (or static class) variable, so with the first example you can do: o = A() o.methodA() print(o.a) With the second example this results into error and variable b runs out of scope after methodB() finishes. About performance... By default instance variables are implemented via dictionary: >>> class A(object): ... def __init__(self): ... self.a = 5 ... >>> o = A() >>> dir(o) ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__g e__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '_ _setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a'] >>> o.__dict__ {'a': 5} >>> o.__dict__.__class__ <class 'dict'> So every access is basically like doing self.__dict__['a'], performance notes here.