Related
I have a function that is going to be the main area of this program, but when I add in a new function that needs to be executed by a button, it prevents the window from appearing, or gives out an error. The function I am trying to get to appear after a button press is new_function.
def bowler():
global bowler_win
global batsmen
bowler_win = Toplevel(master)
batsmen_win_2.withdraw()
variable = StringVar(bowler_win)
variable.set(fielding_team[0])
title = Label(bowler_win, text = "Please choose the bowler").grid(row = 0, column = 1)
w = OptionMenu(bowler_win, variable, *fielding_team)
w.grid(row = 1, column = 1)
def ok2():
current_bowler = variable.get()
for players in batting_team:
if players == current_bowler:
fielding_team.remove(current_bowler)
main_play()
button = Button(bowler_win, text="OK", command=ok2).grid(row = 2, column = 1)
#####CODE ABOVE IS ONLY TO SHOW WHERE THE FUNCTION BELOW IS EXECUTED FROM
def main_play():
while innings != 3:
facing_length = len(batsmen)
while over != over_amount or out_full == True or facing_length <= 1:
main_win = Toplevel(master)
bowler_win.withdraw()
ws = Label(main_win, text = " ").grid(row = 1, column = 1)
title = Label(main_win, text = "Current Game").grid(row = 0, column = 1)
score = Label(main_win, text = "Current Score:").grid(row = 2, column = 1)
line = Label(main_win, text = "--------------").grid(row = 1, column = 1)
score = Label(main_win, text = str(runs) + "/" + str(out)).grid(row = 3, column = 1)
line = Label(main_win, text="--------------").grid(row=4, column=1)
cur_bat = Label(main_win, text = "Facing Batsmen: " + batsmen[0]).grid(row = 5, column = 1)
other_bat = Label(main_win, text = "Other Batsmen: " + batsmen[1]).grid(row = 6, column = 1)
current_patner = Label(main_win, text = "Patnership: " + str(partnership_runs)).grid(row = 7, column = 1)
button = Button(main_win, text = "Next Play", command = new_function).grid(row = 8, column = 1) ###THIS IS WHERE THE NEW FUNCTION IS EXECUTED
If I call the function new_function after the button, the main_win window does not appear, this is the same for if I call new_function above the main_play function, the same error occurs.
If I try to nest new_function below the button, I get the error
UnboundLocalError: local variable 'new_func' referenced before assignment
Even though its a function(and I don't have a variable named that)
If anyone can help, that would be amazing
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()
I'm writing a unit converter using PyQt 4. Here, I'm facing a problem.
class UnitConverter(QtGui.QComboBox):
def __init__(self, parent=None):
super(UnitConverter, self).__init__(parent)
self.unitsdict = {
"mass": {"g": 1, "kg": 1000, "t": 1000000, "oz": 28.3495231, "lb": 453.59237},
"pressure": {"pa": 1, "kpa": 1000, "mpa": 1000000, "bar": 100000, "atm": 101325,
"tor": 133.3223684, "psi": 6894.757, "at": 98066.5}
}
def combo(self, measurement):
for key in self.unitsdict[measurement]:
self.addItem(self.tr(key), self.unitsdict[measurement][key])
def comboConnect(self, table, row, column):
self.names = locals()
#tablevar = "self.table_" + str(row) + "_" + str(column)
self.rowvar = "self.row_" + str(row) + "_" + str(column)
self.columnvar = "self.column_" + str(row) + "_" + str(column)
self.names[self.rowvar] = row
self.names[self.columnvar] = column
self.table = table
self.base = self.itemData(self.currentIndex())
self.currentIndexChanged.connect(self.change)
def change(self):
tobase = self.itemData(self.currentIndex())
try:
self.value = float(self.table.item(self.names[self.rowvar], self.names[self.columnvar]).text())
tovalue = '%f' % (self.value * self.base / tobase)
changeitem = QtGui.QTableWidgetItem(str(tovalue))
self.table.setItem(self.names[self.rowvar], self.names[self.columnvar], changeitem)
except:
pass
self.base = tobase
I want it can automatically calculate the result when I change the index of the combobox.
It works when there is only one QTableWidgetItem connect to it.
table = QTableWidget(10, 3)
combo = Unit converter()
combo.combo("pressure")
table.setCellWidget(5, 0, combo)
combo.comboConnect(table, 5, 1)
But when I connect another QTableWidgetItem, the first one unexpectedly doesn't work any more.
table = QTableWidget(10, 3)
combo = Unit converter()
combo.combo("pressure")
table.setCellWidget(5, 0, combo)
combo.comboConnect(table, 5, 1)
combo.comboConnect(table, 5, 2)
So, I want to know what the problem is. Or, how can I do to make the table(5, 1) work again?
the main problem is that you are overwriting many variables so you only see the last saved data, for example self.rowvar and self.columnvar save the last row and column, instead of updating you must add it to a list or something similar.
class UnitConverter(QtGui.QComboBox):
def __init__(self, table, parent=None):
super(UnitConverter, self).__init__(parent)
self.unitsdict = {
"mass": {"g": 1, "kg": 1000, "t": 1000000, "oz": 28.3495231, "lb": 453.59237},
"pressure": {"pa": 1, "kpa": 1000, "mpa": 1000000, "bar": 100000, "atm": 101325,
"tor": 133.3223684, "psi": 6894.757, "at": 98066.5}
}
self.table = table
self.base = -1
self.items = []
self.currentIndexChanged.connect(self.change)
def combo(self, measurement):
for key in self.unitsdict[measurement]:
self.addItem(self.tr(key), self.unitsdict[measurement][key])
self.base = self.itemData(self.currentIndex())
def comboConnect(self, row, column):
self.items.append((row, column))
def change(self, ix,):
tobase = self.itemData(ix)
factor = self.base / tobase
self.base = tobase
for r, c in self.items:
it = self.table.item(r, c)
try:
value = float(it.text())
tovalue = '%f' % (value * factor)
it.setText(tovalue)
except:
pass
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
table = QtGui.QTableWidget(10, 3)
combo = UnitConverter(table)
combo.combo("pressure")
table.setCellWidget(5, 0, combo)
combo.comboConnect(5, 1)
combo.comboConnect(5, 2)
table.show()
sys.exit(app.exec_())
class phonebook:
def __init__(self,first_name, last_name, street, postcode, city, number):
root = tk.Tk()
root.title('Book')
menubar = tk.Menu(root)
root.config(menu = menubar)
menubar.add_command(label = 'Anlegen', command = self.create)
menubar.add_command(label = 'Bearbeiten', command = self.change)
menubar.add_command(label = 'Löschen')
menubar.add_command(label = 'Sortieren')
menubar.add_command(label = 'Suche')
menubar.add_command(label = 'Hilfe')
root.mainloop()
def printing(self):
account = (self.first_name.get(), self.last_name.get(), self.street.get(), self.postcode.get(), self.city.get(), self.number.get())
accounts.append(account)
for i in accounts:
print(i)
def change(self):
account = accounts[0]
account.first_name = 'test'
self.printing
def create(self):
creation = tk.Toplevel()
tk.Label(creation, text = 'Vorname').grid(row = 1, column = 0)
tk.Label(creation, text = 'Nachname').grid(row = 2, column = 0)
tk.Label(creation, text = 'Stadt').grid(row = 3, column = 0)
tk.Label(creation, text = 'Postleitzahl').grid(row = 4, column = 0)
tk.Label(creation, text = 'Straße').grid(row = 5, column = 0)
tk.Label(creation, text = 'Telefonnummer').grid(row = 6, column = 0)
self.first_name = tk.Entry(creation)
self.last_name = tk.Entry(creation)
self.city = tk.Entry(creation)
self.postcode = tk.Entry(creation)
self.street = tk.Entry(creation)
self.number = tk.Entry(creation)
a = tk.Button(creation, text = 'end', command = self.printing)
self.first_name.grid(row = 1, column = 1)
self.last_name.grid(row = 2, column = 1)
self.city.grid(row = 3, column = 1)
self.postcode.grid(row = 4, column = 1)
self.street.grid(row = 5, column = 1)
self.number.grid(row = 6, column = 1)
a.grid(row = 7, column = 1)
phonebook()
As you can see in my code I'm trying to create and edit objects. The problem is that I cannot create a real object. When I want to create a object with class phonebook, I get this error:
TypeError: __init__() missing 6 required positional arguments: 'first_name', 'last_name', 'street', 'postcode', 'city', and 'number'
What do I have to do so that I don't get this error and so that I can edit the objects?
phonebook must be called with 6 arguments, not 0. You call phonebook(), which causes your code to break. Try calling with something like this:
phonebook("first_name", "last_name", "street", "post_code", "your_city", 123)
substitute in the appropriate values instead of the ones I've provided.
P.S. You won't get much help on this site with a username like that
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...