Radio button indicators not showing up - python

I am new to GUI development and have recently started developing a simple app on Ubuntu by designing the UI with glade and writing the code in python using PyGObject. I have done decently so far until I ran into a mysterious issue.
The indicators of radio buttons on a child window are not showing up. I have been able to toggle them and retrieve which button is active but the indicators themselves do not show up. I have compared the Properties of these buttons with two other radio buttons that I have put up on the main window (look and work as expected) but do not see any difference.
Could someone suggest a way to fix this? I am not sure what all information is required but here are a few images for starters.
Screenshot from glade
General Properties
Common Properties
Screenshot from the executable
Edit: Code which brings up the generate logs window
def on_generate_logs_activate(self, widget):
#Setup generate logs window
self.builder.add_from_file("myprogram6.glade")
self.generate_logs_window = self.builder.get_object("generate_logs_window")
self.generate_logs_window.show_all()
self.all_records = self.builder.get_object("all_records") #Radio1
self.specific_record = self.builder.get_object("specific_record") #Radio2
self.dialog_record_combo = self.builder.get_object("dialog_record_combo")
self.generate = self.builder.get_object("generate")
self.dialog_close = self.builder.get_object("dialog_close")
self.record_set1 = self.builder.get_object("liststore1")
self.dialog_record_combo.set_sensitive(False)
#Setup combotext
self.dialog_record_combo.set_entry_text_column(1)
records = self.get_unprocessed_records()
for record in records:
record=record.split('.')
self.record_set1.append([record[0]])
#Radios
self.all_records.connect("toggled", self.on_all_records_toggled)
self.specific_record.connect("toggled", self.on_specific_record_toggled)
#Generate button
self.generate.connect("clicked", self.on_generate_clicked)
#Close button
self.dialog_close.connect("clicked", self.on_dialog_close_clicked)
Please let me know if you would like me to add more information.

I'm guessing you didn't call window.show_all(). Again, I'm guessing because you didn't post your code, so it's impossible to know.

Look at https://www.youtube.com/watch?v=RxqZ_2fz-ZI
My speculation: you did not structure correctly your application.
Look at video 4 and 5 and you will understand how to structure.
a) python file creation with import at the top. so call it application.py and include
import gi
#
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk as gtk, Gdk as gdk, GLib, GObject as gobject
gobject.threads_init()
import string # not used for now
import os # not used for now
from datetime import datetime, timedelta
import time
import threading..
b) class GUI (called "foo" in the video) hereunder called GUIclass
c) several def linked to the glade file within that class
d) init with import of the glade file
e) main
see few extracts below. look at few applications done with glade / pygtk on github.
class GUIclass:
#
def exit_action(self, widget, data=None):
self.exitdialog.show()
def exit_confirmed(self, widget, data=None):
self.exitdialog.hide()
game_not_cancelled = False
...
gtk.main_quit()
return True
def exit_aborted(self, widget, data=None):
self.exitdialog.hide()
def watch_stop_yes(self, widget, data=None):
#
def deactivate_event_mode(self, widget, data=None):
...
def __init__(self):
...
number_of_period = 2
watch_stop_default = True
add_time_seconds = 0
#
# define all relations between labels and entries and combobox and spinbutton and python variables
builder = gtk.Builder()
builder.add_from_file("/home/family/glade/scoreboard_uwr_180815.glade")
#
# load all windows
self.controlwindow = builder.get_object("scoreboard_control_window")
self.viewwindow = builder.get_object("scoreboard_view_window")
self.logdialog = builder.get_object("scoreboard_log_dialog")
self.logoffdialog = builder.get_object("scoreboard_logoff_confirm")
self.logcanceldialog = builder.get_object("scoreboard_logcancel_confirm")
self.resetdialog = builder.get_object("scoreboard_resetconfirm")
self.exitdialog = builder.get_object("scoreboard_exitconfirm")
#
# declaration of all data from the "scoreboard_control_window"
self.spinbutton_points_team_left = builder.get_object("spinbutton_points_team_left")
self.spinbutton_points_team_right = builder.get_object("spinbutton_points_team_right")
self.spinbutton_timeout_left = builder.get_object("spinbutton_timeout_left")
self.spinbutton_timeout_right = builder.get_object("spinbutton_timeout_right")
self.spinbutton_period_time = builder.get_object("spinbutton_period_time")
self.spinbutton_period = builder.get_object("spinbutton_period")
self.spinbutton_break_time = builder.get_object("spinbutton_break_time")
self.spinbutton_penalty_duration = builder.get_object("spinbutton_penalty_duration")
self.spinbutton_timeout = builder.get_object("spinbutton_timeout")
self.spinbutton_time_penalty = builder.get_object("spinbutton_time_penalty")
self.spinbutton_add_time = builder.get_object("spinbutton_add_time")
self.spinbutton_warning_timepenalty = builder.get_object("spinbutton_warning_timepenalty")
self.spinbutton_warning_break_timeout = builder.get_object("spinbutton_warning_break_timeout")
#
self.togglebutton_start_stop_game = builder.get_object("togglebutton_start_stop_game")
# self.comboboxtext_watch_stop = builder.get_object("comboboxtext_watch_stop")
self.entry_tournament_name = builder.get_object("entry_tournament_name")
self.entry_tournament_contact = builder.get_object("entry_tournament_contact")
self.entry_team_blue_name = builder.get_object("entry_team_blue_name")
self.entry_team_white_name = builder.get_object("entry_team_white_name")
self.entry_name_penalty_player_1_left = builder.get_object("entry_name_penalty_player_1_left")
self.entry_name_penalty_player_2_left = builder.get_object("entry_name_penalty_player_2_left")
self.entry_name_penalty_player_3_left = builder.get_object("entry_name_penalty_player_3_left")
self.entry_name_penalty_player_1_right = builder.get_object("entry_name_penalty_player_1_right")
self.entry_name_penalty_player_2_right = builder.get_object("entry_name_penalty_player_2_right")
self.entry_name_penalty_player_3_right = builder.get_object("entry_name_penalty_player_3_right")
# define here further entries
#
self.label_control_current_time = builder.get_object("label_control_current_time")
self.eventbox_control_left = builder.get_object("eventbox_control_left")
# self.eventbox_blue_team = builder.get_object("eventbox_blue_team")
self.label_control_team_name_left = builder.get_object("label_control_team_name_left")
self.eventbox_control_right = builder.get_object("eventbox_control_right")
self.label_control_team_name_right = builder.get_object("label_control_team_name_right")
self.label_control_tournament_name = builder.get_object("label_control_tournament_name")
self.label_control_tournament_contact = builder.get_object("label_control_tournament_contact")
self.spinbutton_minutes_time_correction = builder.get_object("spinbutton_minutes_time_correction")
self.spinbutton_seconds_time_correction = builder.get_object("spinbutton_seconds_time_correction")
# self.label_special_time_sequence = builder.get_object("label_special_time_sequence")
#
self.label_control_time_penalty_player_1_left = builder.get_object("label_control_time_penalty_player_1_left")
self.label_control_time_penalty_player_2_left = builder.get_object("label_control_time_penalty_player_2_left")
self.label_control_time_penalty_player_3_left = builder.get_object("label_control_time_penalty_player_3_left")
self.label_control_time_penalty_player_1_right = builder.get_object("label_control_time_penalty_player_1_right")
self.label_control_time_penalty_player_2_right = builder.get_object("label_control_time_penalty_player_2_right")
self.label_control_time_penalty_player_3_right = builder.get_object("label_control_time_penalty_player_3_right")
#
# self.label_timeout = builder.get_object("label_timeout")
# self.label_break = builder.get_object("label_break")
# self.label_penalty = builder.get_object("label_penalty")
#
self.spinbutton_points_team_left = builder.get_object("spinbutton_points_team_left")
self.spinbutton_points_team_right = builder.get_object("spinbutton_points_team_right")
self.eventbox_control_points_team_left = builder.get_object("eventbox_control_points_team_left")
self.eventbox_control_points_team_right = builder.get_object("eventbox_control_points_team_right")
self.label_control_points_team_left = builder.get_object("label_control_points_team_left")
self.label_control_points_team_right = builder.get_object("label_control_points_team_right")
self.label_control_special_time_sequence = builder.get_object("label_control_special_time_sequence")
self.eventbox_control_team_name_left = builder.get_object("eventbox_control_team_name_left")
self.eventbox_control_team_name_right = builder.get_object("eventbox_control_team_name_right")
#
# declaration of all data from the view window
self.eventbox_view_team_color_left = builder.get_object("eventbox_view_team_color_left")
self.eventbox_view_team_color_right = builder.get_object("eventbox_view_team_color_right")
self.eventbox_view_points_team_left = builder.get_object("eventbox_view_points_team_left")
self.eventbox_view_points_team_right = builder.get_object("eventbox_view_points_team_right")
self.label_view_period = builder.get_object("label_view_period")
self.label_view_current_time = builder.get_object("label_view_current_time")
self.label_view_points_team_left = builder.get_object("label_view_points_team_left")
self.label_view_timeout_left = builder.get_object("label_view_timeout_left")
self.label_view_timeout_right = builder.get_object("label_view_timeout_right")
self.label_view_points_team_right = builder.get_object("label_view_points_team_right")
self.eventbox_view_team_color_left = builder.get_object("eventbox_view_team_color_left")
self.eventbox_view_team_color_right = builder.get_object("eventbox_view_team_color_right")
self.label_view_team_name_left = builder.get_object("label_view_team_name_left")
self.label_view_team_name_right = builder.get_object("label_view_team_name_right")
self.eventbox_view_team_name_left = builder.get_object("eventbox_view_team_name_left")
self.eventbox_view_team_name_right = builder.get_object("eventbox_view_team_name_right")
self.label_view_tournament_name = builder.get_object("label_view_tournament_name")
self.label_view_tournament_contact = builder.get_object("label_view_tournament_contact")
self.label_view_specific_timesequence = builder.get_object("label_view_specific_timesequence")
self.label_view_status_specific_timesequence = builder.get_object("label_view_status_specific_timesequence")
self.label_view_special_time_sequence = builder.get_object("label_view_special_time_sequence")
self.label_view_time_penalty_player_1_left = builder.get_object("label_view_time_penalty_player_1_left")
self.label_view_time_penalty_player_2_left = builder.get_object("label_view_time_penalty_player_2_left")
self.label_view_time_penalty_player_3_left = builder.get_object("label_view_time_penalty_player_3_left")
self.label_view_time_penalty_player_1_right = builder.get_object("label_view_time_penalty_player_1_right")
self.label_view_time_penalty_player_2_right = builder.get_object("label_view_time_penalty_player_2_right")
self.label_view_time_penalty_player_3_right = builder.get_object("label_view_time_penalty_player_3_right")
#
self.label_view_name_penalty_player_1_left = builder.get_object("label_view_name_penalty_player_1_left")
self.label_view_name_penalty_player_2_left = builder.get_object("label_view_name_penalty_player_2_left")
self.label_view_name_penalty_player_3_left = builder.get_object("label_view_name_penalty_player_3_left")
self.label_view_name_penalty_player_1_right = builder.get_object("label_view_name_penalty_player_1_right")
self.label_view_name_penalty_player_2_right = builder.get_object("label_view_name_penalty_player_2_right")
self.label_view_name_penalty_player_3_right = builder.get_object("label_view_name_penalty_player_3_right")
#
self.button_blue_starts_left = builder.get_object("button_blue_starts_left")
self.button_blue_starts_right = builder.get_object("button_blue_starts_right")
self.button_type_view_invertedcontrolview = builder.get_object("button_type_view_invertedcontrolview")
self.button_type_view_copycontrolview = builder.get_object("button_type_view_copycontrolview")
self.button_separate_game_view_off = builder.get_object("button_separate_game_view_off")
self.button_separate_game_view_on = builder.get_object("button_separate_game_view_on")
self.button_log_functionality_off = builder.get_object("button_log_functionality_off")
self.button_log_functionality_on = builder.get_object("button_log_functionality_on")
self.entry_log_filename = builder.get_object("entry_log_filename")
self.button_nostop_watch = builder.get_object("button_nostop_watch")
self.button_stop_watch = builder.get_object("button_stop_watch")
self.button_activate_timepenalty_player_1_left = builder.get_object("button_activate_timepenalty_player_1_left")
self.button_activate_timepenalty_player_2_left = builder.get_object("button_activate_timepenalty_player_2_left")
self.button_activate_timepenalty_player_3_left = builder.get_object("button_activate_timepenalty_player_3_left")
self.button_activate_timepenalty_player_1_right = builder.get_object(
"button_activate_timepenalty_player_1_right")
self.button_activate_timepenalty_player_2_right = builder.get_object(
"button_activate_timepenalty_player_2_right")
self.button_activate_timepenalty_player_3_right = builder.get_object(
"button_activate_timepenalty_player_3_right")
self.button_clear_timepenalty_player_1_left = builder.get_object("button_clear_timepenalty_player_1_left")
self.button_clear_timepenalty_player_2_left = builder.get_object("button_clear_timepenalty_player_2_left")
self.button_clear_timepenalty_player_3_left = builder.get_object("button_clear_timepenalty_player_3_left")
self.button_clear_timepenalty_player_1_right = builder.get_object("button_clear_timepenalty_player_1_right")
self.button_clear_timepenalty_player_2_right = builder.get_object("button_clear_timepenalty_player_2_right")
self.button_clear_timepenalty_player_3_right = builder.get_object("button_clear_timepenalty_player_3_right")
self.button_stop_special_time_sequence = builder.get_object("button_stop_special_time_sequence")
self.button_start_special_time_sequence = builder.get_object("button_start_special_time_sequence")
self.button_clearreset_special_time_sequence = builder.get_object("button_clearreset_special_time_sequence")
self.button_special_time_sequence_none = builder.get_object("button_special_time_sequence_none")
self.button_special_time_sequence_timeout = builder.get_object("button_special_time_sequence_timeout")
self.button_special_time_sequence_break = builder.get_object("button_special_time_sequence_break")
self.button_special_time_sequence_penalty = builder.get_object("button_special_time_sequence_penalty")
#
self.ChooserButton_read_file_settings = builder.get_object("ChooserButton_read_file_settings")
#
self.label_log_dialog_time = builder.get_object("label_log_dialog_time")
self.entry_log_dialog_remark_referee = builder.get_object("entry_log_dialog_remark_referee")
self.entry_log_dialog_remark_scripter = builder.get_object("entry_log_dialog_remark_scripter")
##################################
# INIT the matrix of all inputs
#
col = 14
row = 10
logdata_array = [[""] * col for _ in range(row)]
#neutralarrayline = ["","","","","","","","","","","","","",""]
#logdata_array = []
#for i in range(9):
# logdata_array.append(neutralarrayline)
self.entry_logarray = []
for i in range(10):
self.entry_logarray.append([])
for j in range(14):
self.entry_logarray[i].append([])
stringglade = str('%(prefix)s%(line)02d_%(column)02d'%{'prefix': "ld", 'line': i, 'column': j})
#print(stringglade)
#"ld"+str(i)+"_"+str(j)
self.entry_logarray[i][j] = builder.get_object(stringglade)
##################################
#self.entry_log_dialog_remark_equipment = builder.get_object("entry_log_dialog_remark_equipment")
self.entry_anytime_line1intolog = builder.get_object("entry_anytime_line1intolog")
self.entry_anytime_line2intolog = builder.get_object("entry_anytime_line2intolog")
self.eventbox_exitbutton = builder.get_object("eventbox_exitbutton")
self.eventbox_resetbutton = builder.get_object("eventbox_resetbutton")
self.button_exit_view_window = builder.get_object("button_exit_view_window")
#
# connect all signals to actions
builder.connect_signals(self)
thread_time_control.connect("update_timers", self.update_timer_labels)
#
# GDK_Escape = 0xff1b
buffer_time_start_special_time_sequence = datetime.now()
#
# datetime data useful for elapsed time calculation and later for log / protocol
start_time_of_the_game = datetime.now()
start_time_control_timepenalty_player1_left = datetime.now()
start_time_control_timepenalty_player2_left = datetime.now()
start_time_control_timepenalty_player3_left = datetime.now()
start_time_control_timepenalty_player1_right = datetime.now()
start_time_control_timepenalty_player2_right = datetime.now()
start_time_control_timepenalty_player3_right = datetime.now()
start_time_of_second_period = datetime.now()
end_time_of_the_game = datetime.now() # usefull for log / protocol
# for running time calculation of the main time counting
buffer_last_time_stop = datetime.now()
buffer_last_time_stop_control_timepenalty_player1_left = datetime.now()
buffer_last_time_stop_control_timepenalty_player2_left = datetime.now()
buffer_last_time_stop_control_timepenalty_player3_left = datetime.now()
buffer_last_time_stop_control_timepenalty_player1_right = datetime.now()
buffer_last_time_stop_control_timepenalty_player2_right = datetime.now()
buffer_last_time_stop_control_timepenalty_player3_right = datetime.now()
buffer_last_time_start = datetime.now()
buffer_last_time_start_control_timepenalty_player1_left = datetime.now()
buffer_last_time_start_control_timepenalty_player2_left = datetime.now()
buffer_last_time_start_control_timepenalty_player3_left = datetime.now()
buffer_last_time_start_control_timepenalty_player1_right = datetime.now()
buffer_last_time_start_control_timepenalty_player2_right = datetime.now()
buffer_last_time_start_control_timepenalty_player3_right = datetime.now()
#
# SEVERAL global parameters and stopwatches to be defined
# FIRST for period time downcounting
# SECOND for special_time_sequence
# 3 for the time penalty players left
# 3 for the time penalty players right
#
ellapsed_period_time_seconds = 0
buffer_last_started_ellapsed_period_time_seconds = 0
period_time_in_second = 15 * 60
period_time_in_second_orig = 15*60
counter_seconds_board = 15 * 60
warning_timepenalty = warning_default_timepenalty
warning_break_timeout = warning_default_break_timeout
#
# diverse parameter of special_time_sequence
timepenalty_maximum_seconds = 120
penalty_maximum_seconds = 45
timeout_maximum_seconds = 1 * 60
break_maximum_seconds = 300
ellapsed_special_time_sequence_seconds = 0
counter_seconds_special_time_sequence = 0
ellapsed_maximum_time_special_sequence_seconds = 300
#
ellapsed_time_penalty_player_1_left_seconds = 0
buffer_last_started_ellapsed_time_penalty_player_1_left_seconds = 0
counter_seconds_time_penalty_player_1_left = 0
#
ellapsed_time_penalty_player_2_left_seconds = 0
buffer_last_started_ellapsed_time_penalty_player_2_left_seconds = 0
counter_seconds_time_penalty_player_2_left = 0
#
ellapsed_time_penalty_player_3_left_seconds = 0
buffer_last_started_ellapsed_time_penalty_player_3_left_seconds = 0
counter_seconds_time_penalty_player_3_left = 0
#
ellapsed_time_penalty_player_1_right_seconds = 0
buffer_last_started_ellapsed_time_penalty_player_1_right_seconds = 0
counter_seconds_time_penalty_player_1_right = 0
#
ellapsed_time_penalty_player_2_right_seconds = 0
buffer_last_started_ellapsed_time_penalty_player_2_right_seconds = 0
counter_seconds_time_penalty_player_2_right = 0
#
ellapsed_time_penalty_player_3_right_seconds = 0
buffer_last_started_ellapsed_time_penalty_player_3_right_seconds = 0
counter_seconds_time_penalty_player_3_right = 0
#
activated_time_penalty_player_1_left_to_enter_or_delete = False
activated_time_penalty_player_2_left_to_enter_or_delete = False
activated_time_penalty_player_3_left_to_enter_or_delete = False
activated_time_penalty_player_1_right_to_enter_or_delete = False
activated_time_penalty_player_2_right_to_enter_or_delete = False
activated_time_penalty_player_3_right_to_enter_or_delete = False
#
time_penalty_player_1_left_initialized = False
time_penalty_player_1_right_initialized = False
time_penalty_player_2_left_initialized = False
time_penalty_player_2_right_initialized = False
time_penalty_player_3_left_initialized = False
time_penalty_player_3_right_initialized = False
#
# diverse helpfull match status or timing
game_started = False
action_start_time_of_the_game_is_ACTIVE = False # toggle button start / stop of the overall timing
running_period_time = False
running_first_period_time = False
running_second_period_time = False
running_penalty = False
running_timeout = False
running_break = False
stopped_special_time_sequence = False
# basic setup of team name
left_team_is_blue = True # at application start
#
running_time_penalty_player_1_left = False
running_time_penalty_player_2_left = False
running_time_penalty_player_3_left = False
running_time_penalty_player_1_right = False
running_time_penalty_player_2_right = False
running_time_penalty_player_3_right = False
#
# buffer for switching the results from right to left in the score viewer
buffer_counter_minutes_time_penalty_player_1 = 0
buffer_counter_seconds_time_penalty_player_1 = 0
buffer_counter_minutes_time_penalty_player_2 = 0
buffer_counter_seconds_time_penalty_player_2 = 0
buffer_counter_minutes_time_penalty_player_3 = 0
buffer_counter_seconds_time_penalty_player_3 = 0
buffer_running_time_penalty_player_1_left = False
buffer_running_time_penalty_player_2_left = False
buffer_running_time_penalty_player_3_left = False
buffer_points_team = 0
################################
# right is white background (and black letter)
self.eventbox_control_right.override_background_color(gtk.StateFlags.NORMAL, gdk.RGBA(1, 1, 1, 1))
self.eventbox_view_team_color_right.override_background_color(gtk.StateFlags.NORMAL, gdk.RGBA(1, 1, 1, 1))
# right point area white
self.eventbox_control_points_team_right.override_background_color(gtk.StateFlags.NORMAL, gdk.RGBA(1, 1, 1, 1))
self.eventbox_view_points_team_right.override_background_color(gtk.StateFlags.NORMAL, gdk.RGBA(1, 1, 1, 1))
self.eventbox_control_team_name_right.override_background_color(gtk.StateFlags.NORMAL, gdk.RGBA(1, 1, 1, 1))
self.eventbox_view_team_name_right.override_background_color(gtk.StateFlags.NORMAL, gdk.RGBA(1, 1, 1, 1))
# right letters of points black in white team
self.label_control_points_team_right.override_color(gtk.StateFlags.NORMAL, gdk.RGBA(0, 0, 0, 1))
self.label_view_points_team_right.override_color(gtk.StateFlags.NORMAL, gdk.RGBA(0, 0, 0, 1))
self.label_control_team_name_right.override_color(gtk.StateFlags.NORMAL, gdk.RGBA(0, 0, 0, 1))
self.label_view_team_name_right.override_color(gtk.StateFlags.NORMAL, gdk.RGBA(0, 0, 0, 1))
#
# left point area blue
self.eventbox_control_left.override_background_color(gtk.StateFlags.NORMAL, gdk.RGBA(0, 0, 1, 1))
self.eventbox_view_team_color_left.override_background_color(gtk.StateFlags.NORMAL, gdk.RGBA(0, 0, 1, 1))
self.eventbox_control_points_team_left.override_background_color(gtk.StateFlags.NORMAL, gdk.RGBA(0, 0, 1, 1))
self.eventbox_view_points_team_left.override_background_color(gtk.StateFlags.NORMAL, gdk.RGBA(0, 0, 1, 1))
# left letters of points white in blue team
self.label_control_points_team_left.override_color(gtk.StateFlags.NORMAL, gdk.RGBA(1, 1, 1, 1))
self.label_view_points_team_left.override_color(gtk.StateFlags.NORMAL, gdk.RGBA(1, 1, 1, 1))
self.eventbox_control_team_name_left.override_background_color(gtk.StateFlags.NORMAL, gdk.RGBA(0, 0, 1, 1))
self.eventbox_view_team_name_left.override_background_color(gtk.StateFlags.NORMAL, gdk.RGBA(0, 0, 1, 1))
self.label_control_team_name_left.override_color(gtk.StateFlags.NORMAL, gdk.RGBA(1, 1, 1, 1))
self.label_view_team_name_left.override_color(gtk.StateFlags.NORMAL, gdk.RGBA(1, 1, 1, 1))
#
#
self.entry_tournament_name.set_text("tournament")
self.label_control_tournament_name.set_text("tournament")
self.label_view_tournament_name.set_text("tournament")
#
self.entry_tournament_contact.set_text("Ms./Mr.")
self.label_control_tournament_contact.set_text("Ms./Mr.")
self.label_view_tournament_contact.set_text("Ms./Mr.")
#
self.entry_team_blue_name.set_text("TeamBLUE")
self.label_control_team_name_left.set_text("TeamBLUE")
self.label_view_team_name_left.set_text("Team BLUE")
#
self.entry_team_white_name.set_text("TeamWHITE")
self.label_control_team_name_right.set_text("TeamWHITE")
self.label_view_team_name_right.set_text("Team WHITE")
#
# make exit button for red
self.eventbox_exitbutton.override_background_color(gtk.StateFlags.NORMAL, gdk.RGBA(1, 0, 0, 1))
#
# orange https://en.wikipedia.org/wiki/X11_color_names test rgb 100% 65% 0%
self.eventbox_resetbutton.override_background_color(gtk.StateFlags.NORMAL, gdk.RGBA(1, 0.65, 0, 1))
# make reset button for red
# self.eventbox_resetbutton.override_background_color(gtk.StateFlags.NORMAL, gdk.RGBA(1, 0, 0, 1))
self.label_control_special_time_sequence.set_text("none")
#
style_provider = gtk.CssProvider()
############################################################################################
############################################################################################
#
# modify that link below at a new installation
#
############################################################################################
css = open('/home/family/glade/scoreboard_uwr/scoreboard_gui_styles.css',
'rb') # rb needed for python 3 support
############################################################################################
############################################################################################
css_data = css.read()
css.close()
style_provider.load_from_data(css_data)
gtk.StyleContext.add_provider_for_screen(gdk.Screen.get_default(), style_provider,
gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
if __name__ == "__main__":
GUI = GUIclass()
GUI.controlwindow.show()
gtk.main()

Related

Changing partial effect lenght with keyframe

FULL CODE
import bpy
bpy.ops.mesh.primitive_plane_add(size=2, location=(0, 0, 0))
bpy.ops.transform.resize(value=(10, 10, 10))
bpy.ops.object.modifier_add(type='COLLISION')
bpy.ops.mesh.primitive_uv_sphere_add(segments=16, ring_count=8, radius=1,
location=(0, 0, 5))
bpy.ops.object.modifier_add(type='SUBSURF')
bpy.context.object.modifiers["Subdivision"].levels = 1
bpy.context.object.modifiers["Subdivision"].render_levels = 3
bpy.ops.object.shade_smooth()
bpy.ops.object.modifier_add(type='COLLISION')
bpy.ops.object.modifier_add(type='SOFT_BODY')
bpy.context.object.modifiers["Softbody"].settings.use_goal = False
bpy.context.object.modifiers["Softbody"].settings.bend = 5
# Particle physics for hair
mod = bpy.context.object.modifiers.new("ParticleSystem", type =
'PARTICLE_SYSTEM')
hair_stngs = mod.particle_system.settings
hair_stngs.type = 'HAIR'
hair_stngs.hair_length = 0
hair_stngs.use_advanced_hair = True
hair_stngs.count = 5000
hair_stngs.hair_step = 12
mod.particle_system.use_hair_dynamics = False
bpy.data.particles["ParticleSettings"].use_regrow_hair = True
bpy.context.object.keyframe_insert(data_path = "hair_length",frame = 0)
bpy.data.particles["ParticleSettings"].hair_length = 0
bpy.context.object.keyframe_insert(data_path = "hair_length",frame = 30)
bpy.data.particles["ParticleSettings"].hair_length = 2
bpy.context.object.keyframe_insert(data_path = "hair_length",frame = 60)
bpy.data.particles["ParticleSettings"].hair_length = 4
When I want to change the data path = hair_length, it does not accept the data path. How can i access the hair lenght?
bpy.context.object.keyframe_insert(data_path = "hair_length",frame = 0)
bpy.data.particles["ParticleSettings"].hair_length = 0
I tried right click and copy data path in partical settings hair lenght but data path didnt recognize by the blender

object in not callable in GUI temperature converter

I'm doing an assignment in Python for a converter between Celsius and Fahrenheit.
The GUI frame appears but the terminal says the FloatField object isn't callable. the error resides within the computeCelsius function within the line that says getNumber(). Trying to ind a solution please help.
from breezypythongui import EasyFrame
class TemperatureConverter(EasyFrame):
"""A termperature conversion program."""
def __init__(self):
"""Sets up the window and widgets."""
EasyFrame.__init__(self, width = 1000, title = "Temperature Converter")
self.addLabel(text = "Celsius", row = 0, column = 0)
self.addLabel(text = "Fahrenheit", row = 0, column = 1)
self.CelsiusField = self.addFloatField(value = 0.0, row = 1, column = 0)
self.FahrenheitField = self.addFloatField(value = 32.0, row = 1, column = 1)
self.grp1 = self.addButton(text = ">>>>", row = 2, column = 0, command = self.computeFahrenheit)
self.grp2 = self.addButton(text = "<<<<", row = 2, column = 1, command = self.computeCelsius)
def computeFahrenheit(self):
inputVal = self.CelsiusField().getNumber()
farh = 9.0/5.0 * inputVal + 32
self.getInputFahrenheit.setValue(farh)
def computeCelsius(self):
inputVal = self.FahrenheitField().getNumber()
cels = (farh - 32) * 5.0/9.0
self.getInputCelsius.setValue(cels)
def main():
"""Instantiate and pop up the window."""
TemperatureConverter().mainloop()
if __name__ == "__main__":
main()

Let the GUI continue working after crashing without having to reset device

My current GUI is to show target tracking from a TI processor to PC via UART. Sometimes, GUI crashes due to UART performance. But everytime I want to reset GUI, I also have to reset my TI device. So I want to modify python code so as to only re-open GUI, enter COM port without having to reset device whenever GUI crashes.
Currently, each time GUI crashes, even though I re-opened GUI but didn't reset device (power off & on), I can not continue tracking.
I put python code for GUI below.In this GUI python program, we have 2 blanks & button to enter UART COM port, 2 buttons to select & send configuration to device. Then it can begin tracking.
I'm considering to modify the part of sendCfg(self), but still not sure how to make it work as my purpose due to my lack of experience in Python & GUI design. Please help me with sample code for this task.
class Window(QDialog):
def __init__(self, parent=None, size=[]):
super(Window, self).__init__(parent)
#when running Gree Demo
self.Gree = 1
# set window toolbar options, and title. #deb_gp
self.setWindowFlags(
Qt.Window |
Qt.CustomizeWindowHint |
Qt.WindowTitleHint |
Qt.WindowMinimizeButtonHint |
Qt.WindowMaximizeButtonHint |
Qt.WindowCloseButtonHint
)
self.setWindowTitle("mmWave People Counting")
print('Python is ', struct.calcsize("P")*8, ' bit')
print('Python version: ', sys.version_info)
gridlay = QGridLayout()
gridlay.addWidget(self.comBox, 0,0,1,1)
gridlay.addWidget(self.statBox, 1,0,1,1)
gridlay.addWidget(self.configBox,2,0,1,1)
gridlay.addWidget(self.plotControlBox,3,0,1,1)
gridlay.addWidget(self.boxTab,4,0,1,1)
gridlay.addWidget(self.spBox,5,0,1,1)
gridlay.addWidget(self.graphTabs,0,1,6,1)
gridlay.addWidget(self.gw, 0, 2, 6, 1)
#gridlay.addWidget(self.demoData, 0,3,1,2)
#gridlay.addWidget(self.hPlot,1,3,4,2)
gridlay.setColumnStretch(0,1)
gridlay.setColumnStretch(1,3)
self.setLayout(gridlay)
#
# left side pane layout
#
def setConnectionLayout(self):
self.comBox = QGroupBox('Connect to Com Ports')
self.uartCom = QLineEdit('') #deb_gp
self.dataCom = QLineEdit('') #deb_gp
self.uartLabel = QLabel('UART COM:')
self.dataLabel = QLabel('DATA COM:')
self.connectStatus = QLabel('Not Connected')
self.connectButton = QPushButton('Connect')
self.connectButton.clicked.connect(self.connectCom)
self.configLabel = QLabel('Config Type:')
self.configType = QComboBox()
self.configType.addItems(["3D People Counting", "SDK Out of Box Demo", "Long Range People Detection", "Indoor False Detection Mitigation", "(Legacy) 2D People Counting", "(Legacy): Overhead People Counting"])
self.comLayout = QGridLayout()
self.comLayout.addWidget(self.uartLabel,0,0)
self.comLayout.addWidget(self.uartCom,0,1)
self.comLayout.addWidget(self.dataLabel,1,0)
self.comLayout.addWidget(self.dataCom,1,1)
self.comLayout.addWidget(self.configLabel,2,0)
self.comLayout.addWidget(self.configType,2,1)
self.comLayout.addWidget(self.connectButton,3,0)
self.comLayout.addWidget(self.connectStatus,3,1)
self.comBox.setLayout(self.comLayout)
def setConfigLayout(self):
self.configBox = QGroupBox('Configuration')
self.selectConfig = QPushButton('Select Configuration')
self.sendConfig = QPushButton('Send Configuration')
self.selectConfig.clicked.connect(self.selectCfg)
self.sendConfig.clicked.connect(self.sendCfg)
self.configTable = QTableWidget(5,2)
#set parameter names
self.configTable.setItem(0,0,QTableWidgetItem('Radar Parameter'))
self.configTable.setItem(0,1,QTableWidgetItem('Value'))
self.configTable.setItem(1,0,QTableWidgetItem('Max Range'))
self.configTable.setItem(2,0,QTableWidgetItem('Range Resolution'))
self.configTable.setItem(3,0,QTableWidgetItem('Max Velocity'))
self.configTable.setItem(4,0,QTableWidgetItem('Velcoity Resolution'))
self.configLayout = QVBoxLayout()
self.configLayout.addWidget(self.selectConfig)
self.configLayout.addWidget(self.sendConfig)
self.configLayout.addWidget(self.configTable)
#self.configLayout.addStretch(1)
self.configBox.setLayout(self.configLayout)
def updateGraph(self, parsedData):
updateStart = int(round(time.time()*1000))
self.useFilter = 0
classifierOutput = []
pointCloud = parsedData[0]
targets = parsedData[1]
indexes = parsedData[2]
numPoints = parsedData[3]
numTargets = parsedData[4]
self.frameNum = parsedData[5]
fail = parsedData[6]
classifierOutput = parsedData[7]
fallDetEn = 0
indicesIn = []
if (fail != 1):
#left side
pointstr = 'Points: '+str(numPoints)
targetstr = 'Targets: '+str(numTargets)
self.numPointsDisplay.setText(pointstr)
self.numTargetsDisplay.setText(targetstr)
#right side fall detection
peopleStr = 'Number of Detected People: '+str(numTargets)
if (numTargets == 0):
fdestr = 'Fall Detection Disabled - No People Detected'
elif (numTargets == 1):
fdestr = 'Fall Detection Enabled'
fallDetEn = 1
elif (numTargets > 1):
fdestr = 'Fall Detected Disabled - Too Many People'
#self.numDetPeople.setText(peopleStr)
#self.fallDetEnabled.setText(fdestr)
if (len(targets) < 13):
targets = []
classifierOutput = []
if (fail):
return
#remove static points
if (self.configType.currentText() == '3D People Counting'):
if (not self.staticclutter.isChecked()):
statics = np.where(pointCloud[3,:] == 0)
try:
firstZ = statics[0][0]
numPoints = firstZ
pointCloud = pointCloud[:,:firstZ]
indexes = indexes[:,:self.previousFirstZ]
self.previousFirstZ = firstZ
except:
firstZ = -1
#point cloud persistence
fNum = self.frameNum%10
if (numPoints):
self.previousCloud[:5,:numPoints,fNum] = pointCloud[:5,:numPoints]
self.previousCloud[5,:len(indexes),fNum] = indexes
self.previousPointCount[fNum]=numPoints
#plotting 3D - get correct point cloud (persistent points and synchronize the frame)
if (self.configType.currentText() == 'SDK3xPeopleCount'):
pointIn = pointCloud
else:
totalPoints = 0
persistentFrames = int(self.persistentFramesInput.currentText())
#allocate new array for all the points
for i in range(1,persistentFrames+1):
totalPoints += self.previousPointCount[fNum-i]
pointIn = np.zeros((5,int(totalPoints)))
indicesIn = np.ones((1, int(totalPoints)))*255
totalPoints = 0
#fill array
for i in range(1,persistentFrames+1):
prevCount = int(self.previousPointCount[fNum-i])
pointIn[:,totalPoints:totalPoints+prevCount] = self.previousCloud[:5,:prevCount,fNum-i]
if (numTargets > 0):
indicesIn[0,totalPoints:totalPoints+prevCount] = self.previousCloud[5,:prevCount,fNum-i]
totalPoints+=prevCount
if (self.graphFin):
self.plotstart = int(round(time.time()*1000))
self.graphFin = 0
if (self.threeD):
try:
indicesIn = indicesIn[0,:]
except:
indicesIn = []
self.get_thread = updateQTTargetThread3D(pointIn, targets, indicesIn, self.scatter, self.pcplot, numTargets, self.ellipsoids, self.coordStr, classifierOutput, self.zRange, self.gw, self.plotByIndex.isChecked(), self.plotTracks.isChecked(), self.bbox,self.boundaryBoxes[0]['checkEnable'].isChecked())
self.get_thread.done.connect(self.graphDone)
self.get_thread.start(priority=QThread.HighestPriority-1)
else:
npc = pointIn[0:2,:]
print (np.shape(npc))
self.legacyThread = update2DQTGraphThread(npc, targets, numTargets, indexes, numPoints, self.trailData, self.activeTrail, self.trails, self.scatter2D, self.gatingScatter)
self.legacyThread.done.connect(self.graphDone)
self.legacyThread.start(priority=QThread.HighestPriority-1)
else:
return
#pointIn = self.previousCloud[:,:int(self.previousPointCount[fNum-1]),fNum-1]
#state tracking
if (numTargets > 0):
self.lastFrameHadTargets = True
else:
self.lastFrameHadTargets = False
if (numTargets):
self.lastTID = targets[0,:]
else:
self.lastTID = []
def graphDone(self):
plotend = int(round(time.time()*1000))
plotime = plotend - self.plotstart
try:
if (self.frameNum > 1):
self.averagePlot = (plotime*1/self.frameNum) + (self.averagePlot*(self.frameNum-1)/(self.frameNum))
else:
self.averagePlot = plotime
except:
self.averagePlot = plotime
self.graphFin = 1
pltstr = 'Average Plot time: '+str(plotime)[:5] + ' ms'
fnstr = 'Frame: '+str(self.frameNum)
self.frameNumDisplay.setText(fnstr)
self.plotTimeDisplay.setText(pltstr)
def resetFallText(self):
self.fallAlert.setText('Standing')
self.fallPic.setPixmap(self.standingPicture)
self.fallResetTimerOn = 0
def updateFallThresh(self):
try:
newThresh = float(self.fallThreshInput.text())
self.fallThresh = newThresh
self.fallThreshMarker.setPos(self.fallThresh)
except:
print('No numberical threshold')
def connectCom(self):
#get parser
self.parser = uartParserSDK(type=self.configType.currentText())
self.parser.frameTime = self.frameTime
print('Parser type: ',self.configType.currentText())
#init threads and timers
self.uart_thread = parseUartThread(self.parser)
if (self.configType.currentText() != 'Replay'):
self.uart_thread.fin.connect(self.parseData)
self.uart_thread.fin.connect(self.updateGraph)
self.parseTimer = QTimer()
self.parseTimer.setSingleShot(False)
self.parseTimer.timeout.connect(self.parseData)
try:
uart = "COM"+ self.uartCom.text() #deb_gp
data = "COM"+ self.dataCom.text() #deb_gp
#TODO: find the serial ports automatically.
self.parser.connectComPorts(uart, data)
self.connectStatus.setText('Connected') #deb_gp
self.connectButton.setText('Disconnect') #deb_gp
#TODO: create the disconnect button action
except:
self.connectStatus.setText('Unable to Connect')
if (self.configType.currentText() == "Replay"):
self.connectStatus.setText('Replay')
if (self.configType.currentText() == "Long Range People Detection"):
self.frameTime = 400
#
# Select and parse the configuration file
# TODO select the cfgfile automatically based on the profile.
def selectCfg(self):
try:
self.parseCfg(self.selectFile())
except:
print('No cfg file selected!')
def selectFile(self):
fd = QFileDialog()
filt = "cfg(*.cfg)"
filename = fd.getOpenFileName(directory='./../chirp_configs',filter=filt) #deb_gp - added folder name
return filename[0]
def parseCfg(self, fname):
cfg_file = open(fname, 'r')
self.cfg = cfg_file.readlines()
counter = 0
chirpCount = 0
for line in self.cfg:
args = line.split()
if (len(args) > 0):
if (args[0] == 'cfarCfg'):
zy = 4
#self.cfarConfig = {args[10], args[11], '1'}
elif (args[0] == 'AllocationParam'):
zy=3
#self.allocConfig = tuple(args[1:6])
elif (args[0] == 'GatingParam'):
zy=2
#self.gatingConfig = tuple(args[1:4])
elif (args[0] == 'SceneryParam' or args[0] == 'boundaryBox'):
self.boundaryLine = counter
self.profile['leftX'] = float(args[1])
self.profile['rightX'] = float(args[2])
self.profile['nearY'] = float(args[3])
self.profile['farY'] = float(args[4])
self.setBoundaryTextVals(self.profile)
self.boundaryBoxes[0]['checkEnable'].setChecked(True)
elif (args[0] == 'staticBoundaryBox'):
self.staticLine = counter
elif (args[0] == 'profileCfg'):
self.profile['startFreq'] = float(args[2])
self.profile['idle'] = float(args[3])
self.profile['adcStart'] = float(args[4])
self.profile['rampEnd'] = float(args[5])
self.profile['slope'] = float(args[8])
self.profile['samples'] = float(args[10])
self.profile['sampleRate'] = float(args[11])
print(self.profile)
elif (args[0] == 'frameCfg'):
self.profile['numLoops'] = float(args[3])
self.profile['numTx'] = float(args[2])+1
elif (args[0] == 'chirpCfg'):
chirpCount += 1
elif (args[0] == 'sensorPosition'):
self.profile['sensorHeight'] = float(args[1])
self.profile['az_tilt'] = float(args[2])
self.profile['elev_tilt'] = float(args[3])
counter += 1
maxRange = self.profile['sampleRate']*1e3*0.9*3e8/(2*self.profile['slope']*1e12)
#update boundary box
self.drawBoundaryGrid(maxRange)
#update chirp table values
bw = self.profile['samples']/(self.profile['sampleRate']*1e3)*self.profile['slope']*1e12
rangeRes = 3e8/(2*bw)
Tc = (self.profile['idle']*1e-6 + self.profile['rampEnd']*1e-6)*chirpCount
lda = 3e8/(self.profile['startFreq']*1e9)
maxVelocity = lda/(4*Tc)
velocityRes = lda/(2*Tc*self.profile['numLoops']*self.profile['numTx'])
self.configTable.setItem(1,1,QTableWidgetItem(str(maxRange)[:5]))
self.configTable.setItem(2,1,QTableWidgetItem(str(rangeRes)[:5]))
self.configTable.setItem(3,1,QTableWidgetItem(str(maxVelocity)[:5]))
self.configTable.setItem(4,1,QTableWidgetItem(str(velocityRes)[:5]))
#update sensor position
self.az_tilt.setText(str(self.profile['az_tilt']))
self.elev_tilt.setText(str(self.profile['elev_tilt']))
self.s_height.setText(str(self.profile['sensorHeight']))
def sendCfg(self):
try:
if (self.configType.currentText() != "Replay"):
self.parser.sendCfg(self.cfg)
self.configSent = 1
self.parseTimer.start(self.frameTime)
except:
print ('No cfg file selected!')
# Needed ?? deb_gp
# def setParser(self, uParser):
# self.parser = uParser
def parseData(self):
self.uart_thread.start(priority=QThread.HighestPriority)
def whoVisible(self):
if (self.threeD):
self.threeD = 0
else:
self.threeD = 1
print('3d: ', self.threeD)
if __name__ == '__main__':
if (compileGui):
appctxt = ApplicationContext()
app = QApplication(sys.argv)
screen = app.primaryScreen()
size = screen.size()
main = Window(size=size)
main.show()
exit_code = appctxt.app.exec_()
sys.exit(exit_code)
else:
app = QApplication(sys.argv)
screen = app.primaryScreen()
size = screen.size()
main = Window(size=size)
main.show()
sys.exit(app.exec_())

PyQT table update crash easyly

i first use PyQT4 .
i'm create a QTableWidget to show runing message...
when my program run, it ill crash Within ten minutes.
i try diable my TableUpdate function , and it's don't crash again.
there is my code please help me
class table_work(QThread):
TableDataSignal = pyqtSignal()
def __init__(self,main_self):
# QThread.__init__(self)
super(table_work, self).__init__(main_self)
self.main_self = main_self
self.table_update_list = list()
#pyqtSlot(dict)
def update_table_thread_o(self,work):
try:
row_pos = work['row_position']
data = work['data']
table_key_sort = work['key_sort']
this_table = work['table']
k = 0
for table_key in table_key_sort:
this_table.setItem(row_pos, k, QTableWidgetItem(unicode(data[table_key])))
k += 1
del work
except:
pass
def update_table_thread(self):
main_self = self.main_self
table_work_list = self.table_update_list
while 1:
for work in self.table_update_list:
row_pos = work['row_position']
data = work['data']
table_key_sort = work['key_sort']
this_table = work['table']
k = 0
for table_key in table_key_sort:
this_table.setItem(row_pos, k, QTableWidgetItem(unicode(data[table_key])))
k += 1
time.sleep(0.5)
def run(self):
self.update_table_thread()
this's update table message
def update_table(self,address,change_obj=None,tabe_name='auto_card'):
sample_dict = dict()
table_key_sort = list()
now_table_sort = 0
if tabe_name == "auto_bot":
this_table = self.auto_bot_procc_table
table_data_list = self.auto_bot_procc_table_list
now_table_sort = self.auto_bot_now_table_sort
sample_dict['address'] = address
sample_dict['money'] = 0
sample_dict['run_time'] = 0
sample_dict['item_cd'] = u"60分鐘後"
sample_dict['stat'] = "Ready..."
sample_dict['sort'] = now_table_sort
table_key_sort.append('address')
table_key_sort.append('money')
table_key_sort.append('run_time')
table_key_sort.append('item_cd')
table_key_sort.append('stat')
if tabe_name == "auto_card":
this_table = self.process_table
table_data_list = self.now_procc_table_list
now_table_sort = self.now_table_sort
sample_dict['address'] = address
sample_dict['done_num'] = 0
sample_dict['pre_item'] = ""
sample_dict['procc'] = "Ready"
sample_dict['mission_procc'] = u"待命.."
sample_dict['mission_num'] = 0
sample_dict['mission_line'] = 0
sample_dict['update_time'] = db.get_time()
sample_dict['sort'] = now_table_sort
sample_dict['option'] = ""
table_key_sort.append('address')
table_key_sort.append('done_num')
table_key_sort.append('pre_item')
table_key_sort.append('mission_procc')
table_key_sort.append('procc')
table_key_sort.append('mission_num')
table_key_sort.append('mission_line')
table_key_sort.append('update_time')
if address not in table_data_list:
this_table.insertRow(sample_dict['sort'])
table_data_list[address] = sample_dict
sample_dict['sort'] = self.auto_bot_now_table_sort
self.auto_bot_now_table_sort += 1
acc_data = table_data_list[address]
if change_obj != None:
key = change_obj['key']
val = change_obj['val']
if key in acc_data:
acc_data[key] = val
acc_data['update_time'] = db.get_time()
rowPosition = acc_data['sort']
temp = dict()
temp['row_position'] = rowPosition
temp['data'] = acc_data
temp['key_sort'] = table_key_sort
temp['table'] = this_table
self.TableDataSignal.emit(temp)
del temp
Some time i get a ANS.
i'm a PYQT newbie , After this period of various projects experience.
I understand if you don't use Main Thread to Change UI, Always use sign/emit
even your code is worked,but always use sign/emit, Otherwise there will be a series of disasters.
you just like
class sample(QtCore.QThread):
table_data_change = QtCore.pyqtSignal(dict)
def __init__(self,main_win):
self.main = main_win
self.table_data_change.connect(self.main.change_fn)
def test(self):
data = dict()
data['btn'] = .....
data['val'] = .....
self.table_data_change.emit(data)
Save your time !

Python timetable pass start and finish time that pressed button relevant to position

For my coursework i am making a booking system and i have been messing around trying to make a page which shows current week lessons and when the button is clicked it comes up with that students details on a separate page.But i don't know how to go about passing that time into my open page sub(which writes a txt file which is going to be used for SQL to get the students details). The current way i have done it just passes the max times into the sub.
from tkinter import *
import datetime
class Application(Frame):
def __init__(self, master):
""" Initialize the frame. """
super(Application, self).__init__(master)
self.grid()
self.timetable_button_gen_weekdays()
self.timetable_button_gen_weekends()
def timetable_button_gen_weekdays(self):
c = datetime.datetime(100,1,1,16,00,00)
self.Monday_lbl = Label(self, text = "Monday")
self.Monday_lbl.grid(row = 1, column = 0)
self.Tuesday_lbl = Label(self, text = "Tuesday")
self.Tuesday_lbl.grid(row = 2, column = 0)
self.Wednesday_lbl = Label(self, text = "Wednesday")
self.Wednesday_lbl.grid(row = 3, column = 0)
self.Thursday_lbl = Label(self, text = "Thursday")
self.Thursday_lbl.grid(row = 4, column = 0)
self.Friday_lbl = Label(self, text = "Friday")
self.Friday_lbl.grid(row = 5, column = 0)
for k in range(8):
b = c + datetime.timedelta(minutes = (30 * k))
d = b + datetime.timedelta(minutes = (30))
self.i_time_weekdays_lbl = Label(self, text = b.time().strftime('%H:%M')+" to "+d.time().strftime('%H:%M'))
self.i_time_weekdays_lbl.grid(row = 0, column = k + 1)
for i in range(5):
for a in range(8):
b = c + datetime.timedelta(minutes = (30 * a))
d = b + datetime.timedelta(minutes = (30))
bttn_i_a = Button(self, text = "available",command = lambda: self.OpenPage(b.time().strftime('%H:%M'),d.time().strftime('%H:%M')))
bttn_i_a.grid(row = i + 1, column = a + 1)
bttn_i_a.config(height = 2, width = 10)
def timetable_button_gen_weekends(self):
c = datetime.datetime(100,1,1,10,00,00)
self.Saturday_lbl = Label(self, text = "Saturday")
self.Saturday_lbl.grid(row = 8, column = 0)
self.Sunday_lbl = Label(self, text = "Sunday")
self.Sunday_lbl.grid(row = 9, column = 0)
self.weekend_lbl = Label(self, text = "Weekend")
self.weekend_lbl.grid(row = 6, column = 1, sticky = W)
for k in range(10):
b = c + datetime.timedelta(minutes = (30 * k))
d = b + datetime.timedelta(minutes = (30))
self.i_time_weekdays_lbl = Label(self, text = b.time().strftime('%H:%M')+" to "+d.time().strftime('%H:%M'))
self.i_time_weekdays_lbl.grid(row = 7, column = k + 1)
for i in range(2):
for a in range(10):
b = c + datetime.timedelta(minutes = (30 * a))
d = b + datetime.timedelta(minutes = (30))
bttn_i_a = Button(self, text = "available",command = lambda: self.OpenPage(b.time().strftime('%H:%M'),d.time().strftime('%H:%M')))
bttn_i_a.grid(row = i + 8, column = a + 1)
bttn_i_a.config(height = 2, width = 10)
def OpenPage(self,startime,finishtime):
file = open("PassTimes.txt","w")
file.write(startime)
file.write("\n")
file.write(finishtime)
print(startime)
print(finishtime)
filepath = "PresentStudent.py"
global_namespace = {"__file__": filepath, "__name__": "__main__"}
with open(filepath, 'rb') as file:
exec(compile(file.read(), filepath, 'exec'), global_namespace)
root = Tk()
root.title("test")
root.geometry("2000x2000")
app = Application(root)
root.mainloop()
Welcome to SO.
General
IMHO, running the main routine of "PresentStudent.py" does not look that clean.
It works, but a main routine is built for when the script is called directly, not when it is imported and used in some other script.
Are you aware of the modules functionality in python?
I would recommend creating a function in PresentStudent.py that does what you are doing inside your main routine. Give the function parameters to pass the .txt-Filename.
e.g.
def presentStudentCall(inputFile):
and use it inside your script like:
#!/usr/bin/python
# -*- coding: utf-8 -*-
# here we import PresentStudent.py, as we import it __main__ will not run
import PresentStudent
#[...]
def OpenPage(self, stime, etime):
#[...]
# Instead of executing a file we call the function from the module
PresentStudent.presentStudentCall(file)
If you want to display the data inside a second frame, you could also declare a class in PresentStudent.py and use it like:
def OpenPage(self, stime, etime):
#[...]
student=PresentStudent.Student() # assuming to name the class "Student"
student.presentStudentCall(file)
Your question itself
using the lambda does not need to be the best way. In matters of scope and garbage collecting your code only passes the last generated "b"s and "c"s to the definition.
What you could do to make it work is calculating the sender item in OpenPage:
To achieve that, I recommend having arrays for your time spans storing starting times.
Like
c = datetime.datetime(100,1,1,16,00,00)
self.weektimes = ["%s"%(c+datetime.timedelta(minutes=30*k)) for k in range(8)]
self.weekendtimes = ["%s"%((c+datetime.timedelta(minutes=30*k)) for k in range(10)]
First you need to bind the click event to the widget(in that case your button)
bttn_i_a.bind("<Button-1>", self.OnPage)
Your OpenPage could then look like this:
def OpenPage(self, event):
import time
# With that, we get the row and column where we clicked in
grid_info=event.widget.grid_info()
# week or weekend?
if grid_info["row"] > 5: #may depend on amount of headers
_timearray=self.weekendtimes
else:
_timearray=self.weektimes
# get the column
col=grid_info["column"]
# get the startTime
stime=_timearray[col]
# end time is +30 minutes
etime="%s"%(time.strptime("%s"%stime, "%H:%M")+time.struct_time(tm_min=30))
# now call the handler...

Categories

Resources