def configure_styles(self): """Create the ttk.style styles.""" style = ThemedStyle(self.master) style.set_theme("default") style.configure('TButton', foreground="black", background="white", borderwidth=0, highlightthickness=0, font=('MS Reference Sans Serif', 15))
def configure_styles(self): style = ThemedStyle(self.master) style.set_theme("default") style.configure( 'TButton', foreground=self.FOREGROUND_COLOR, background=self.BACKGROUND_COLOR, borderwidth=0, highlightthickness=0, font=('MS Reference Sans Serif', 15) ) style.configure( 'Plus.TButton', font=('MS Reference Sans Serif', 20) ) style.configure( 'File.TButton', font=self.BUTTON_FONT ) style.configure( 'Current.File.TButton', background=self.FOREGROUND_COLOR, foreground=self.BACKGROUND_COLOR )
self.window = HistViewer(self, self.filename) else: self.header['text'] = 'No File Chosen!' self.window = FileViewer(self, '') #self.window = ShowHistogram(self, self.file_contents) # initialise frame to show historgam def Refresh(self): if (self.window.winfo_exists()): self.window.grid_forget() self.window.destroy() #destroy the current window to refresh m_file = open(self.filename, 'r', errors='ignore') #reopen updated file self.file_contents = m_file.read() self.window = FileViewer( self, self.file_contents) # initialise frame to show file m_file.close() root = tk.Tk() root.geometry("1200x600") root.configure(background='#eff0f1') style = ThemedStyle(root) style.set_theme('breeze') style.configure('TButton', foreground='black') my_gui = RootFrame(root) root.mainloop()
class MainController(tk.Tk): """ It is the main window of the application, it plays the role of manager. All page of the application are displayed in this window. It links the interface with the server or client script. """ def __init__(self): super().__init__() # List containing the data entered by the user to create or connect to server. self.data_server = [] self.data_client = [] # Define variables self.current_page = None self.server = None self.client = None self.stop = False # Set the color themes of the application. self.current_color = 0 # Set the default application language. self.languages = ["English", "Français"] self.current_language = 0 # Define font family of the application. self.ft_title = ("Courier 18 underline") self.ft_subtitle = ("Courier 14 underline") self.ft_footer = ("Courier 10") # Defines the main container for the application. self.container = tk.Frame(self) self.container.pack(fill="both") # Add an icon to the application. try: self.iconbitmap("application/icon/icon_app.ico") # Avoid an error if the icon has not been found. except tk.TclError: pass # Configure main parameters of the application. self.title("Online Chat") self.geometry("790x600") self.resizable(width=False, height=False) self.protocol("WM_DELETE_WINDOW", self.on_closing) # First display the home menu page. self.show_frame(HomeMenu) def show_frame(self, frame_page): """ Display a new page in the window. Arg: - frame_page (tk.Frame): The frame containing the page you want to display. """ # Update the application theme. self.value_combobox = ["Light Mode", "Dark Mode"] self.name_theme = ["arc", "black"][self.current_color] self.bg_color = ["#F5F6F7", "#424242"][self.current_color] self.canvas_color = ["#FFFFFF", "#626262"][self.current_color] self.msg_other_color = ["#FFFDCD", "#D1D6DA"][self.current_color] self.font_color = ["#5C616C", "#A6A6A6"][self.current_color] self.msg_font_color = ["#000000", "#000000"][self.current_color] self.border_color = ["#DDE3E9", "#2A2A2A"][self.current_color] # Define the style. self.style = ThemedStyle() self.style.set_theme(self.name_theme) self.style.configure("TLabel", foreground=self.font_color) self.style.configure("TButton", font=("Courier 11 bold"), foreground=self.font_color) self.style.configure("TNotebook", font=("Courier 9"), foreground=self.font_color) self.style.configure("TScrollbar", bg=self.bg_color) self.style.configure("TSeparator", bg=self.font_color) self.config(bg=self.bg_color) # If a page is alredy displayed, it is destroyed. if self.current_page: self.current_page.destroy() # Change the current page and display the page. self.current_page = frame_page(self) self.current_page.pack(expand=True, fill="both", anchor="center") def create_server(self): """Create a new server.""" self.server = Server(*self.data_server) # Create the server connection and report the connection status to inform the user. self.server.create_connection() self.msg_report = self.server.msg_report[self.current_language] # If the server is correctly launched, change the page of the application. if self.server.is_launched: self.after(200, lambda: self.show_frame(ServerMenu)) # Else reset variable. else: self.server = None self.data_server = [] def create_client(self): """Create a new instance of a user.""" self.client = Client(*self.data_client) # Create connection and connect the client to server. And, informs him of the connection status. self.client.create_connection() self.msg_report = self.client.msg_report[self.current_language] # If the server is correctly launched, change the page of the application. if self.client.is_connected: self.after(200, lambda: self.show_frame(ClientMenu)) # Else reset variable. else: self.client = None self.data_client = [] def go_home(self): """Close the connection with server and return to home menu.""" # Close the connection. if self.on_closing(False): self.stop = False # Change the current page of the application. self.show_frame(HomeMenu) def on_closing(self, quit=True): """ Close the open instances (server or client) then, the application. Arg: - quit (bool): If true destroy and close the application. """ try: exit = True # If a server exist. if self.server: exit = messagebox.askyesno( ["Online Chat", "Quitter le serveur"][self.current_language], [ "Are you sure you want to stop and exit the server?", "Voulez-vous vraiment arrêter et quitter le serveur ?" ][self.current_language]) # Close the connection. if exit: self.server.close_server() self.data_server = [] self.server = None # If a client exist. elif self.client: exit = messagebox.askyesno( ["Online Chat", "Quitter le serveur"][self.current_language], [ "Are you sure you want to quit the server ?", "Voulez-vous vraiment quitter le serveur ?" ][self.current_language]) # Close the connection. if exit: self.client.close() self.data_client = [] self.client = None # Close the application. if exit and quit: self.stop = True self.quit() return True elif exit and not quit: self.stop = True return True # Forces the application to stop. except Exception as e: print(e) messagebox.showerror("Online Chat", e) sys.exit()
def __init__(self, dark_theme=False): self.queue = Queue() self.root = Tk() self.root.title('Renovação Minerva') self.root.resizable(False, False) self.root.bind('<Escape>', self.close) self.var_save_credentials = IntVar() style = ThemedStyle(self.root) if dark_theme: # TODO(erick): This theme is somewhat beautiful, but its progressbar # is ugly as hell. style.theme_use('equilux') else: style.theme_use('arc') style.configure('TButton', font=default_font) style.configure('TLabel', font=default_font) main_frame = ttk.Frame(self.root) main_frame.pack(expand=True, fill=BOTH) logo_img = ImageTk.PhotoImage(Image.open('logo.png')) logo = ttk.Label(main_frame, image=logo_img, padding=default_pad) logo.pack() first_row = ttk.Frame(main_frame) first_row.pack(fill=X) id_label = ttk.Label(first_row, text='Id:', relief=default_relief) id_label.pack(side=LEFT, padx=default_pad, pady=default_pad) self.id_entry = ttk.Entry(first_row, validate='key', font=default_font) self.id_entry['validatecommand'] = (self.id_entry.register( self.validate_id), '%P', '%d') self.id_entry.config(width=11) self.id_entry.pack(side=RIGHT, padx=default_pad) second_row = ttk.Frame(main_frame) second_row.pack(fill=X) pass_label = ttk.Label(second_row, text='Senha:', relief=default_relief) pass_label.pack(side=LEFT, padx=default_pad, pady=default_pad) self.pass_entry = ttk.Entry(second_row, font=default_font) self.pass_entry.config(width=11, show="*") self.pass_entry.pack(side=RIGHT, padx=default_pad) self.pass_entry.bind('<Return>', self.renew_callback) third_row = ttk.Frame(main_frame) third_row.pack(fill=X) save_checkbox = ttk.Checkbutton(third_row, text='Salvar dados', variable=self.var_save_credentials) save_checkbox.pack(side=LEFT, padx=default_pad, pady=default_pad) fourth_row = ttk.Frame(main_frame) fourth_row.pack(fill=X) self.renew_button = ttk.Button(fourth_row, text='Renovar', command=self.renew_callback) self.renew_button.pack(side=RIGHT, padx=default_pad, pady=default_pad) self.renew_button.bind('<Return>', self.renew_callback) self.progress_row = ttk.Frame(main_frame) self.progressbar = ttk.Progressbar(self.progress_row, orient='horizontal', mode='indeterminate') self.progressbar.pack(expand=True, fill=X) self.progress_status = ttk.Label(self.progress_row, relief=SUNKEN) self.progress_status.pack(expand=True, fill=X) self.progress_status['text'] = ' ' has_credentials = self.fill_credentials() self.var_save_credentials.set(has_credentials) if has_credentials: self.renew_button.focus_set() else: self.id_entry.focus_set() self.root.mainloop()
w, h = root.winfo_screenwidth(), root.winfo_screenheight() root.geometry("%dx%d+0+0" % (w, h)) # Setting Theme style = ThemedStyle(root) style.set_theme("ubuntu") #Bild anlegen und positionieren image1 = PhotoImage(file="bbb.png") panel1 = Label(root, image=image1, background="#F2F2F2") panel1.config(height=900, width=1920) panel1.place(x=-3, y=25, relheight=1, relwidth=1) style.configure('TButton', width=15, borderwidth=1, background="#F2F2F2", font=('Verdana', 16)) Themed_Btn = ttk.Button(root, text='EXIT', command=quit) Themed_Btn.place(x=1645, y=0) Themed_Btn1 = ttk.Button(root, text='INFO', command=info) Themed_Btn1.place(x=1645, y=43) Themed_Btn1 = ttk.Button(root, text='STATISTIK', command=plot) Themed_Btn1.place(x=1645, y=86) import tkinter.ttk as ttk myColor = '#F2F2F2' s = ttk.Style()
def __init__(self): """ Initializes the graphical user interface """ # main interface object self.parent = Tk() self.parent.state = False # strings manager strings = Strings() self._ = strings.get # theme style = ThemedStyle(self.parent) style.set_theme("arc") # button style style.configure("TButton", font=self.button_font_family) # special button style style.configure(self.special_button_style, font=(self.special_button_font_family, self.special_button_font_size, self.special_button_font_weight)) # make buttons change foreground when hovered style.map("TButton", foreground=[("active", self.special_button_active)]) # root window initialization Frame.__init__(self, self.parent) w = config.get_int("minimum_window_width", 1280) # minimum width for the Tk parent h = config.get_int("minimum_window_height", 800) # minimum height for the Tk parent # get screen width and height ws = self.parent.winfo_screenwidth() # width of the screen hs = self.parent.winfo_screenheight() # height of the screen self.parent.geometry("%dx%d+0+0" % (ws, hs)) # set the dimensions of the window self.parent.minsize(w, h) # minimum size of the window # window title self.parent.title(self.window_title) # menu bar self.menu_bar = Menu(self.parent, font=self.menu_font_family) self.file_menu = Menu(self.menu_bar, tearoff=0, font=self.menu_font_family) self.menu_bar.add_cascade(label=self._("menu.cascade.file"), menu=self.file_menu) self.edit_menu = Menu(self.menu_bar, tearoff=0, font=self.menu_font_family) self.menu_bar.add_cascade(label=self._("menu.cascade.edit"), menu=self.edit_menu) self.view_menu = Menu(self.menu_bar, tearoff=0, font=self.menu_font_family) self.menu_bar.add_cascade(label=self._("menu.cascade.view"), menu=self.view_menu) self.view_menu.add_command(label=self._("menu.zoom_in"), accelerator="Ctrl++", command=self.zoom_in) self.view_menu.add_command(label=self._("menu.zoom_out"), accelerator="Ctrl+-", command=self.zoom_out) self.filter_menu = Menu(self.menu_bar, tearoff=0, font=self.menu_font_family) self.menu_bar.add_cascade(label=self._("menu.cascade.filter"), menu=self.filter_menu) self.taxonomy_menu = Menu(self.menu_bar, tearoff=0, font=self.menu_font_family) self.menu_bar.add_cascade(label=self._("menu.cascade.taxonomy"), menu=self.taxonomy_menu) self.parent.config(menu=self.menu_bar) # make the frame take the whole window self.pack(fill=BOTH, expand=1) # input frame self.input_frame = None # output frame self.output_frame = Frame(self) self.output_frame.pack(fill=BOTH, anchor=N, expand=1) self.output_frame.grid_propagate(False) # ensure a consistent GUI size self.output_frame.grid_rowconfigure( 0, weight=30) # implement stretchability self.output_frame.grid_rowconfigure( 1, weight=1) # implement stretchability self.output_frame.grid_columnconfigure(0, weight=1) self.text = Text(self.output_frame, borderwidth=3, relief=SUNKEN, cursor="arrow", selectbackground=self.select_background, inactiveselectbackground=self.select_background) # Text widget self.text.grid(row=0, column=0, sticky="nsew", padx=self.padding, pady=(self.padding, 0)) self.text.config(font=(self.text_font_family, self.text_font_size), undo=True, wrap=WORD, bg=self.text_background, fg=self.text_foreground, state=DISABLED) # create a Scrollbar and associate it with text self.scrollbar = Scrollbar(self.output_frame, command=self.text.yview) self.scrollbar.grid(row=0, rowspan=3, column=1, sticky=NSEW) self.text["yscrollcommand"] = self.scrollbar.set # status bar self.status = Label(self.output_frame, font=(self.label_font_family, self.label_font_size, "bold")) self.status.grid(row=1, column=0, pady=0) # binds any typing to the command input field to the update_commands method sv = StringVar() sv.trace("w", lambda name, index, mode, sv=sv: self.update_commands()) # input frame self.input_frame = Frame(self) self.input_frame.pack(fill=X, side=BOTTOM) # makes the command input field self.entry = Entry(self.input_frame, font=(self.entry_font_family, self.entry_font_size), textvariable=sv, state=DISABLED) self.entry.bind( "<Return>", self.return_pressed ) # binds the Return key to the return_pressed() method self.entry.bind( "<KP_Enter>", self.return_pressed ) # binds the Return key to the return_pressed() method self.entry.bind( "<Tab>", self.tab_pressed) # binds the Tab key to the tab_pressed() method self.entry.pack(fill=X, side=BOTTOM, padx=2, pady=2) # places the input field self.entry.focus_set() # sets the focus on the input field # creates the frame containing buttons self.commands = Frame(self.input_frame) self.commands.pack(fill=X, side=BOTTOM) self.prompt = StringVar() self.prompt_label = Label(self.commands, font=(self.prompt_font_family, self.prompt_font_size, self.prompt_font_weight), textvariable=self.prompt) self.prompt_label.pack(side=LEFT, padx=(10, 15), pady=10) # creates the frame containing special buttons self.special_commands = Frame(self.input_frame) self.special_commands.pack(fill=X, side=BOTTOM) # default bindings self.parent.bind(config.get_string("toggle_fullscreen", "<F11>"), lambda event: self.toggle_fullscreen()) self.parent.bind(config.get_string("exit_prompt", "<Escape>"), lambda event: self.exit_prompt()) self.parent.bind(config.get_string("zoom_in", "<Control-KP_Add>"), lambda event: self.zoom_in()) self.parent.bind( config.get_string("zoom_out", "<Control-KP_Subtract>"), lambda event: self.zoom_out()) # binding mouse clicks and movement self.text.bind("<Button-1>", self.record_click) self.text.bind("<Button-2>", self.record_click) self.clickable_text_tag = "clickable_text_tag" self.text.bind("<ButtonRelease-1>", self.mouse_left_click) self.text.bind("<ButtonRelease-3>", self.mouse_right_click) self.text.bind("<Motion>", self.mouse_motion) self.last_click_index = "1.0" self.last_release_index = "1.0" self.command_list = [] # list of potential commands self.action = None # default command action self.default_action = None # default command action self.free_input = False # sets whether it's possible to input anything in the entry # basic text tags self.add_tag(GraphicalUserInterface.STRONG, font_weight="bold") self.add_tag(GraphicalUserInterface.ITALIC, font_weight="italic") self.add_tag(GraphicalUserInterface.HIGHLIGHT, background=self.highlight_background) self.text.tag_raise(SEL) # makes sure the selection is fisible
class GUI: """ Graphical User Interface, makes the communication easier for the bus driver in order to reduce the time the driver has to put into communicating with the system. designed in a 3 color scheme, black, green, and white has a background glow thats used to show the bus driver important updates, that need his attention default color is green, changes the color to red when there's a passenger that needs to be picked up and changes the color to gray when the bus is offline. has a welcome window that his purpose is to acquire some information regarding the bus from the driver. 3 entries that get the Bus ID, the line number and the starting station of the bus. And a Finish Button that saves the information and starts the bus system with the given information After the finish is clicked, the window will close and a loading screen is displayed while the main window is loading. the main window holds on top a display that shows the locations of all the relevant buses and passengers. Next Station button that moves the bus to the next station. a square with the purpose to make sure that the bus will stop at the station if there's a passengers. server broadcasts section that shows all the messages recieved from the server place to send messages to the server that consists of a send button and an entry to type the text into. also displays some statistics. and a big red exit button. """ __BLACK = "#000000" __GREEN = "#105e29" __GREEN1 = "#1DB954" def __init__(self): """ creates a GUI class instance :return: GUI """ self.__line, self.__id, self.__station = None, None, None self.__bus = None self.__font_name = "Bahnschrift SemiBold SemiConden" self.__headlines = None self.asking_to_reconnect = False self.__passengers_count_stringvar = None self.__buses_count_stringvar = None self.__session_time_stringvar = None self.__window = None self.__finished_window = None self.__lost_connection_window = None self.__kicked_window = None self.__server_broadbast_stringvars_dict = dict() #those dictionaries store the location regarding plament widget groups on the screen self.__statistics_coords = {"x": 540, "y": 408} self.__updating_statistics_coords ={"x": 680, "y": 331} self.__next_btn_coords = {"x": 29, "y": 177} self.__exit_btn_coords = {"x": 29, "y": 490} self.__broadcast_section_coords = {"x": 44, "y": 427} self.__server_messages_coords = {"x": 66, "y": 322, "jump": 34} self.__table_coords = {"x": 26, "y": 74, "width" : 744, "height":59} def start(self): """ starts the gui starts by asking for starting information for the bus, after that creates a bus instance with the given information after that starts the loading process for the rest of the program components. :return: None """ self.config_first_data() if self.__line == None: sys.exit("Ended by user") self.__window = Tk() self.__window.iconbitmap(f'images bus\\icon.ico') # put stuff to icon self.__window.title("Bus Client") self.__window.resizable(OFF, OFF) self.__start_loading_screen() self.__window.mainloop() self.stop() def stop(self): """ stops the run of the gui and tells the bus to stop as well. at the end closes the code :return: None """ self.__bus.stop = True if self.__finished_window != None and self.__finished_window.state() == "normal": self.__finished_window.destroy() if self.__window != None and self.__window.state() == "normal": self.__window.destroy() if self.__lost_connection_window != None and self.__lost_connection_window.state() == "normal": self.__lost_connection_window.destory() if self.__kicked_window != None and self.__kicked_window.state() == "normal": self.__kicked_window.destroy() sys.exit("closed by user") def __start_loading_screen(self): """ Starts the loading proccess. At first shows the loading image, waits for 10ms and then starts loading all the widgets and the properties of the program. :return: None """ loading_img = ImageTk.PhotoImage(PIL.Image.open(r"Images bus\loading screen.png")) self.__window.geometry(f"{loading_img.width()}x{loading_img.height()}") self.__bg_label = Label(self.__window, image=loading_img, bg="#192b3d") self.__bg_label.place(x=0, y=0) self.__window.after(10, self.__finish_loading_screen) self.__window.mainloop() def __finish_loading_screen(self, launch_bus=True): """ starts the bus object, places all the labels, buttons, data tables, entries and initializes all the values needed for the rest of the run :return: False """ if launch_bus: self.__bus = Bus(self, self.__id, self.__line, self.__station) self.__bus.start() self.__headlines = [str(x) for x in range(1, self.__bus.max_number_of_stations + 1)] self.__passengers_count_stringvar = StringVar() self.__buses_count_stringvar = StringVar() self.__server_broadbast_stringvar1 = StringVar() self.__server_broadbast_stringvar2 = StringVar() self.__session_time_stringvar = StringVar() #init all the images self.__bg_nobody_is_waiting_img = ImageTk.PhotoImage(PIL.Image.open(r"Images bus\nobody is waiting.png")) self.__bg_lost_connection_img = ImageTk.PhotoImage(PIL.Image.open(r"Images bus\lost connection.png")) self.__bg_stop_at_the_next_station_img = ImageTk.PhotoImage(PIL.Image.open(r"Images bus\stop at the next station.png")) self.__next_btn_img = ImageTk.PhotoImage(PIL.Image.open(r"Images bus\next station.png")) self.__exit_btn_img = ImageTk.PhotoImage(PIL.Image.open(r"Images bus\exit btn.png")) self.__send_btn_img = ImageTk.PhotoImage(PIL.Image.open(r"Images bus\send btn.png")) #place the widgets on the window self.__create_table() self.__update_table() self.__place_buttons() self.__place_labels() self.__place_free_text_section() self.__window.geometry(f"{self.__bg_nobody_is_waiting_img.width()}x{self.__bg_nobody_is_waiting_img.height()}") self.__update_bg() #start the updates loop that will keep the widgets updated self.__loop() def __create_table(self): """ creates and places the table that display the locations of the buses and the passengers for the line. uses the ttk. widgets Treeview combined with a scrollbar. and the ThemedStyle lib in order to give the dark themed look to the widget. :return: None """ base_x = self.__table_coords["x"] base_y = self.__table_coords["y"] base_width = self.__table_coords["width"] base_height = self.__table_coords["height"] self.__tree_style = ThemedStyle(self.__window) self.__tree_style.set_theme("black") self.__tree_style.configure("mystyle.Treeview", highlightthickness=0, bd=0, font=(self.__font_name, 11)) # Modify the font of the body self.__tree_style.configure("mystyle.Treeview", background="black", fieldbackground="black", foreground=GUI.__GREEN1) self.__tree_style.configure("mystyle.Treeview.Heading", font=(self.__font_name, 13, 'bold'), foreground=GUI.__GREEN1) # Modify the font of the headings scrollX = ttk.Scrollbar(self.__window, orient=HORIZONTAL) self.__tree = Treeview(self.__window, show="headings", columns=self.__headlines, xscrollcommand=scrollX.set, style = "mystyle.Treeview") self.__tree.place(x=base_x, y=base_y, width=base_width, height=base_height) scrollX.config(command=self.__tree.xview) scrollX.place(x=base_x, y=base_y+base_height, width=base_width) def __place_buttons(self): """ Places the main buttons on the screen. next_button - tells the bus to move onto the next station and tell the server that he moved exit_button - closes the gui and the server :return: None """ self.__next_button = tkinter.Button(self.__window, image=self.__next_btn_img, command=self.__bus.next_station, borderwidth=0, background = "#000000", activebackground = "#083417") self.__next_button.place(x=self.__next_btn_coords["x"], y=self.__next_btn_coords["y"]) self.__exit_button = tkinter.Button(self.__window, command=self.stop, image=self.__exit_btn_img, borderwidth=0, background=GUI.__BLACK, activebackground=GUI.__BLACK, fg="red") self.__exit_button.place(x=self.__exit_btn_coords["x"], y=self.__exit_btn_coords["y"]) def __update_labels(self): """ updates all the labels in the program passenger count - shows how many passengers are waiting for the bus buses count - shows how many buses are active in the line session time - displays the session time of the driver server messages - shows the messages received from the server updates the StringVars instead of recreating the label. the messages label is actually more than just 1 label, but all the labels and the StringVars are stored in the same dict the reason is that breaking down the messages into a couple layers allows more flexible formatting :return: None """ #statistics self.__passengers_count_stringvar.set(str(self.__bus.count_people())) self.__buses_count_stringvar.set(str(self.__bus.count_buses())) self.__session_time_stringvar.set(f"{self.__bus.session_time}") #server messages messages = [] for message in self.__bus.server_free_text_messages: if time.time() - message["time"] > Bus.MESSAGE_TTL: #Removes old messages self.__bus.server_free_text_messages.remove(message) messages.append(f"{time.strftime('%H:%M:%S', time.localtime(message['time']))}: {message['text']} \n") #makes sure that all the labels will be addressed, if there's not enough information for them fills with "" while len(messages) <Bus.MAX_MESSAGE_COUNT: messages.append("") #updates the StringVars for i in range(0,Bus.MAX_MESSAGE_COUNT): self.__server_broadbast_stringvars_dict[i].set(messages[i]) def __loop(self): """ the main GUI loop, run in the main thread and updates data on the screen (labels, table and background) runs twice per second but can be easily changes if needed will stop looping only when the self.__bus.stop is equal to True :return: None """ if self.__bus.stop: return try: self.__update_table() self.__update_bg() self.__update_labels() self.__after_job = self.__window.after(500, self.__loop) except Exception as e: print(f"Done looping because: {e}") def __place_labels(self): """ creates labels, configures them and places them at the places they're supposed to be. labels that are placed - passengers_count shows the passengers count in the line - buses_count shows the bus count of the buses in the line - server_messages shows the messages received from the server - line_label shows the line number - id_label shows the bus id - session_time_label shows the session time :return: None """ # statistics labels self.__passengers_count_stringvar.set(str(self.__bus.count_people())) self.__buses_count_stringvar.set(str(self.__bus.count_buses())) #changing statistics base_x = self.__updating_statistics_coords["x"] base_y = self.__updating_statistics_coords["y"] passengers_count_label = Label(self.__window, textvariable=self.__passengers_count_stringvar, fg=GUI.__GREEN, bg=GUI.__BLACK, font=(self.__font_name, 13, "bold")) buses_count_label = Label(self.__window, textvariable=self.__buses_count_stringvar, fg=GUI.__GREEN, bg=GUI.__BLACK, font=(self.__font_name, 13, "bold")) passengers_count_label.place(x=base_x, y=base_y) buses_count_label.place(x=base_x + 42, y=base_y + 28) #broadcasts base_x =self.__server_messages_coords["x"] base_y = self.__server_messages_coords["y"] jump = self.__server_messages_coords["jump"] for i in range(0,Bus.MAX_MESSAGE_COUNT): self.__server_broadbast_stringvars_dict[i] = StringVar() Label(self.__window, fg=GUI.__GREEN, bg = GUI.__BLACK, font=(self.__font_name, 15, "bold"), textvariable=self.__server_broadbast_stringvars_dict[i]).place(x=base_x, y=base_y+jump*i) # statistics base_x = self.__statistics_coords["x"] base_y = self.__statistics_coords["y"] Label(self.__window, text=str(self.__line), fg=GUI.__GREEN, bg = GUI.__BLACK, font=(self.__font_name, 12, "bold")).place(x=base_x, y=base_y) Label(self.__window, text=str(self.__id), fg=GUI.__GREEN, bg = GUI.__BLACK, font=(self.__font_name, 12, "bold")).place(x=base_x-14, y=base_y+20) Label(self.__window, textvariable=self.__session_time_stringvar, fg=GUI.__GREEN, bg=GUI.__BLACK, font=(self.__font_name, 12, "bold")).place(x=base_x+37, y=base_y+39) def __place_free_text_section(self): """ places the free text section has a button and an entry that will send messages to the server if needed upon a button click the data in the entry will be sent to the server as a message from the bus. :return: None """ self.__message_entry = Entry(self.__window, width = 30, borderwidth=0, background = "black", insertbackground ="#1DB954", foreground="#1DB954",font = (self.__font_name, 14)) self.__send_broadcast_button = Button(self.__window, image=self.__send_btn_img, borderwidth=0, background = "#000000", activebackground = "#083417", command=self.__send_free_text_to_server) base_x =self.__broadcast_section_coords["x"] base_y =self.__broadcast_section_coords["y"] self.__message_entry.place(x=base_x, y=base_y) self.__send_broadcast_button.place(x=base_x-3, y=base_y +29) def __send_free_text_to_server(self): """ harvests the data from the self.__message_entry, clears the entry then tells the bus to send the message to the server :return: None """ if self.__bus.connected: data = self.__message_entry.get() print(f"broad casting data: {data}") if not self.__bus.send_free_text(data): print("failed to send") else: self.__message_entry.delete(0, 'end') else: print("failed to send") def __update_table(self): """ recalculates the way the display table is supposed to look and places all the widgets into the table. :return: None """ self.__headlines = [str(x) for x in range(1, self.__bus.max_number_of_stations + 1)] self.__tree.config(columns=self.__headlines) for headline in self.__headlines: self.__tree.heading(headline, text=headline) self.__tree.column(headline, anchor="center", stretch=False, width=47) data = self.__bus.display_passengers() for i in self.__tree.get_children(): self.__tree.delete(i) self.__tree.insert("", END, values=data) def __update_bg(self): """ changes the background according to the state of the bus currently has only 3 states but more states can be easily added nobody is waiting - will display a greenish background with the message "nobody is waiting" when there are no passengers waiting stop at the next station - will display a red background with the message "somebody is waiting" when there's a passenger at the next station lost connection - will display a gray background with the message "lost connection" when the bus loses connection or gets kicked. :return: None """ if self.__bus.connected and not self.__bus.kicked: if self.__bus.next_station_people_count==0: self.__bg_label["image"] = self.__bg_nobody_is_waiting_img elif self.__bus.next_station_people_count > 0: self.__bg_label["image"] = self.__bg_stop_at_the_next_station_img else: self.__bg_label["image"] = self.__bg_lost_connection_img def display_lost_connection(self): """ creates a window saying that the bus has lost connection to the server has a button that says "Reconnect" and will try to reconnect to the server. if failed to reconnect a new message will show saying "failed to reestablish connection to the server" :return: None """ if self.__bus.stop == True: return self.__lost_connection_window = Tk() self.__lost_connection_popup_img = ImageTk.PhotoImage(PIL.Image.open(r"Images bus\Lost connection popup.png"),master=self.__lost_connection_window) self.__lost_connection_window.geometry(f"{self.__lost_connection_popup_img.width()}x{self.__lost_connection_popup_img.height()}") self.__lost_connection_window.iconbitmap(r'Images bus\icon.ico') # put stuff to icon self.__lost_connection_window.title("Lost Connection to the server") self.__lost_connection_window.resizable(OFF, OFF) self.__bg_label_lost_connection = Label(self.__lost_connection_window, image=self.__lost_connection_popup_img, bg="white") self.__bg_label_lost_connection.place(x=0, y=0) self.__reconnect_img = ImageTk.PhotoImage(PIL.Image.open(r"Images bus\reconnect.png"), master=self.__lost_connection_window) self.__reconnect_button = tkinter.Button(self.__lost_connection_window, command=lambda: self.__try_to_reconnect("PostLogin"), image=self.__reconnect_img, borderwidth =0, activebackground="white") self.__reconnect_button.place(x=152, y=101) self.__lost_connection_window.mainloop() if not self.__bus.connected: sys.exit("closed by user") def failed_to_connect(self, firstattempt = True): """ creates a window saying that the bus has failed to establish the first connection to the server. has a button that says "Reconnect" and will try to reconnect to the server. if failed to reconnect a new message will show saying "failed to reestablish connection to the server" :return: None """ if self.__bus.stop == True: return if not firstattempt: self.__failed_to_reconnect_img = ImageTk.PhotoImage( PIL.Image.open(r"Images bus\failed to reestablish.png"), master=self.__failed_to_connect_window) self.__bg_label_failed_to_connect["image"] = self.__failed_to_reconnect_img return self.__failed_to_connect_window = Tk() self.__failed_to_connect_img = ImageTk.PhotoImage(PIL.Image.open(r"Images bus\failed to establish.png"), master=self.__failed_to_connect_window) self.__failed_to_connect_window.geometry( f"{self.__failed_to_connect_img.width()}x{self.__failed_to_connect_img.height()}") self.__failed_to_connect_window.iconbitmap(r'Images bus\icon.ico') # put stuff to icon self.__failed_to_connect_window.title("Failed To Connect") self.__failed_to_connect_window.resizable(OFF, OFF) self.__bg_label_failed_to_connect = Label(self.__failed_to_connect_window, image=self.__failed_to_connect_img, bg="white") self.__bg_label_failed_to_connect.place(x=0, y=0) self.__reconnect_img = ImageTk.PhotoImage(PIL.Image.open(r"Images bus\reconnect.png"), master=self.__failed_to_connect_window) self.__reconnect_button = tkinter.Button(self.__failed_to_connect_window, command=lambda: self.__try_to_reconnect("PreLogin"), image=self.__reconnect_img, borderwidth=0, activebackground="white") self.__reconnect_button.place(x=152, y=101) self.__failed_to_connect_window.mainloop() if not self.__bus.connected: sys.exit("closed by user") def display_kicked(self, reason: str): """ creates a window saying that the bus has been kicked from the server has a button that says "Reconnect" and will try to reconnect to the server. if failed to reconnect a new message will show saying "failed to reestablish connection to the server". takes the reason that the bus had been kicked as a parameter, currently has no use, but here to make future development easier. :param reason: str :return: None """ if self.__bus.stop == True: return self.__kicked_window = Tk() self.__kicked_img = ImageTk.PhotoImage(PIL.Image.open(r"Images bus\kicked.png"),master=self.__kicked_window) self.__kicked_window.geometry(f"{self.__kicked_img.width()}x{self.__kicked_img.height()}") self.__kicked_window.iconbitmap(r'Images bus\icon.ico') # put stuff to icon self.__kicked_window.title("kicked") self.__kicked_window.resizable(OFF, OFF) self.__bg_label_kicked = Label(self.__kicked_window, image=self.__kicked_img, bg="white") self.__bg_label_kicked.place(x=0, y=0) self.__reconnect_img = ImageTk.PhotoImage(PIL.Image.open(r"Images bus\reconnect.png"), master=self.__kicked_window) self.__reconnect_button = tkinter.Button(self.__kicked_window, command=lambda: self.__try_to_reconnect("Kicked"), image=self.__reconnect_img, borderwidth =0, activebackground="white") self.__reconnect_button.place(x=152, y=101) self.__kicked_window.mainloop() if not self.__bus.connected: sys.exit("closed by user") def display_finished(self): """ opens a window that shows the finished image and all the statistics that come with it. shows the session time, and how many people the bus picked up during his ride. has an exit button that closes the program and ends the session. used as the last window in the program, nothing will open after this window is closed. return: None """ self.__window.after_cancel(self.__after_job) self.__window.destroy() finished_font = ("Bauhaus 93", 30) self.__finished_window = Tk() self.__finished_img = ImageTk.PhotoImage(PIL.Image.open(r"Images bus\finished.png")) self.__finished_exit_img = ImageTk.PhotoImage(PIL.Image.open(r"Images bus\exit finished.png")) self.__finished_window.geometry(f"{self.__finished_img.width()}x{self.__finished_img.height()}") self.__finished_window.iconbitmap(r'Images bus\icon.ico') # put stuff to icon self.__finished_window.title("Finished") self.__finished_window.resizable(OFF, OFF) bg_label = Label(self.__finished_window, image=self.__finished_img, bg="#1DB954") bg_label.place(x=0, y=0) self.__people_count_label = Label(self.__finished_window, text=str(self.__bus.total_people_count), bg="#1DB954", fg="#000000", font=finished_font) self.__session_time_label = Label(self.__finished_window, text=str(self.__bus.session_time), fg="#1DB954", bg="#000000", font=finished_font) self.__finish_button = tkinter.Button(self.__finished_window, image=self.__finished_exit_img, command=self.stop, borderwidth=0, activebackground="gray", fg="red") self.__finish_button.place(x=276, y=462) self.__people_count_label.place(x=494, y=190) self.__session_time_label.place(x=560, y=320) self.__finished_window.mainloop() if not self.__bus.connected: sys.exit("closed by user") def __try_to_reconnect(self, status): """ tries to reconnect the bus back to the server takes the status of the program when the command was called, can be "PreLogin"\"PostLogin"\"Kicked" used in case if failed to reconnect, it makes sure that the correct window will be updated. :param status: str return: Bool """ if status == "PreLogin": if self.__bus.start(first_attempt = False): self.__finish_loading_screen(launch_bus=False) self.__failed_to_connect_window.destroy() elif self.__bus.reconnect(): if status =="PostLogin": self.__lost_connection_window.destroy() elif status == "Kicked": self.__kicked_window.destroy() else: print(f"ughh..... i dunno what to do, status: {status} unrecognized") self.__bus.asking_user_to_reconnect = False else: if status == "PostLogin": self.__failed_to_reconnect_img = ImageTk.PhotoImage(PIL.Image.open(r"Images bus\failed to reestablish.png"), master=self.__lost_connection_window) self.__bg_label_lost_connection["image"]=self.__failed_to_reconnect_img elif status == "Kicked": self.__failed_to_reconnect_img = ImageTk.PhotoImage( PIL.Image.open(r"Images bus\failed to reestablish.png"), master=self.__kicked_window) self.__bg_label_kicked["image"] = self.__failed_to_reconnect_img else: print(f"ughh..... i dunno what to do, status: {status} unrecognized") def config_first_data(self): """ the first thing that the uses sees when he runs the client. opens a window asking the user to give some information about the bus he's driving and the line he's working for has 3 entries and a finish button - id_entry the bus id - line_entry the line that the bus works for - station_entry the station number that the driver starts from - finish_button passes the entries to the __set_up_data method that takes the data, saves it and closes the window :return: None """ window = Tk() back_ground_img = ImageTk.PhotoImage(PIL.Image.open(r"Images bus\opening screen.png")) finish_img = ImageTk.PhotoImage(PIL.Image.open(r"Images bus\finish btn.png")) window.geometry(f"{back_ground_img.width()}x{back_ground_img.height()}") window.iconbitmap(f'images bus\\icon.ico') # put stuff to icon window.title("User Setup") window.resizable(OFF, OFF) back_ground_label = Label(window, image=back_ground_img, bg=GUI.__BLACK) back_ground_label.place(x=0, y=0) station_entry = Entry(window, width=8, borderwidth=0, background = "black", foreground="#1DB954", insertbackground ="#1DB954", font = (self.__font_name, 22)) station_entry.insert(END, "1") station_entry.place(x=570, y=397) id_entry = Entry(window, width=20, borderwidth=0, background = "black", foreground="#1DB954", insertbackground ="#1DB954", font = (self.__font_name, 22)) id_entry.insert(END, str(random.randint(1, 11111111))) id_entry.place(x=295, y=247) line_entry = Entry(window, width=14, borderwidth=0, background = "black", foreground="#1DB954", insertbackground ="#1DB954", font = (self.__font_name, 22)) line_entry.insert(END, "14") line_entry.place(x=484, y=323) finish_button = tkinter.Button(window, image =finish_img, activebackground=GUI.__GREEN, borderwidth=0, background = GUI.__GREEN, command=lambda: self.__set_up_data(id_entry, station_entry, line_entry, window)) finish_button.place(x=299, y=478) window.mainloop() def __set_up_data(self, id_entry, station_entry, line_entry, window): """ checks that all the values given match the expected (all of them are numbers) after that stores them as part of the class variables and and closes the given window in case if the given values don't match the expectation then a new window will be shown saying that the values must be numbers. :param id_entry: Entry :param station_entry: Entry :param line_entry: Entry :param window: Tk :return: None """ try: self.__id = int(id_entry.get()) self.__line = int(line_entry.get()) self.__station = int(station_entry.get()) window.destroy() except: error_window = Tk() error_window.geometry("200x80") error_window.iconbitmap(r'Images bus\icon.ico') # put stuff to icon error_window.title("Error") error_window.resizable(OFF, OFF) error_window.configure(bg="red") error_label = Label(error_window, text="Error\n\nValues must be numbers") error_label.configure(bg="red") error_label.place(x=20, y=20)
else: resultado['text'] = f"Dados inválidos!" root = Tk() root.title('SQ System') # root.geometry('200x350') root.configure(background='#202020') root.call('tk', 'windowingsystem') root.overrideredirect style = ThemedStyle() style.set_theme('clam') style.configure("my.TLabel", font=('HYWenHei-85W', 24, 'bold'), background='#202020', foreground='white', borderwidth=0) style.configure("my.TButton", font=('HYWenHei-85W', 24, 'bold'), background='#202020', foreground='#202020', relief=GROOVE) style.configure("my.TEntry", font=('HYWenHei-85W', 14, 'bold'), padding=5) # IMAGENS img_login = PhotoImage(file="img/login.png") img_user = PhotoImage(file="img/user.png") img_password = PhotoImage(file="img/password.png") button = PhotoImage(file="img/button.png")
import requests from bs4 import BeautifulSoup as soup import tkinter as tk from PIL import ImageTk, Image import tkinter.ttk as ttk from ttkthemes import ThemedStyle window = tk.Tk() window.configure(background="#e6e6fa") theme = ThemedStyle(window) theme.set_theme("radiance") bg = tk.PhotoImage(file='/home/mitsu/PycharmProjects/SCRAPPER/corona.png') window.tk.call('wm', 'iconphoto', window._w, bg) theme.configure('TButton', background='#e6e6fa') theme.configure('TButton', foreground='black') theme.configure('TCombobox', background='#e6e6fa') window.title("Covid-19 info") lab1 = tk.Label(window, text="COVID-19 Cases,Deaths and Recovered.", font=("arial", 16), fg='black', bg="#e6e6fa") lab1.grid(row=0, column=1, columnspan=2) for_ = "https://www.worldometers.info/coronavirus/?utm_campaign=homeAdUOA?Si" ref = requests.get(for_) ren = ref.content