def check_replay(self): """Displays 'play again' label with 'yes' and 'no' buttons. Selecting 'yes' runs restart_program function, selecting 'no' exits the program.""" play_again_label = Label(self.canvas, text='Play Again?', font=[self.font, 20], bg=self.background_color, fg=self.text_color, justify='center') play_again_label.place(relx=0.418, rely=0.8) yes_button = Button(self.canvas, bg=self.button_color, fg=self.text_color, font=[self.font, 15], text='Yes', width=80, height=60, command=self.restart_program) no_button = Button(self.canvas, bg=self.button_color, fg=self.text_color, font=[self.font, 15], text='No', width=80, height=60, command=sys.exit) yes_button.place(relx=.395, rely=0.85) no_button.place(relx=0.5, rely=0.85)
def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller canvas = Canvas(self, height=HEIGHT, width=WIDTH) canvas.pack() background_frame = Frame(self, bg="#7ECFEC") background_frame.place(relwidth=1, relheight=1) upper_frame = Frame(self, bg="Black") upper_frame.place(relx=0.5, rely=0.02, relwidth=0.9, relheight=0.07, anchor='n') welcomelabel = Label(upper_frame, text="Corpus", fg="Black", font=("Modern", 15, "bold")) welcomelabel.place(relwidth=1, relheight=1) middle_frame = Frame(self, bg='white') middle_frame.place(relx=0.5, rely=0.1, relwidth=0.9, relheight=0.8, anchor='n') textlabel = Label( middle_frame, text= "If this is your first time performing LDA, \n please select some csv files" " to build your corpus.\n Click 'Select Files' to do so. \n \n" "Otherwise your saved data will be used, \n so you can skip this step and the preprocessing.", bg='white', font=('Modern', 12)) textlabel.place(relwidth=1, relheight=1) lower_frame = Frame(self, bg='Black', bd=5) lower_frame.place(relx=0.5, rely=0.92, relwidth=0.5, relheight=0.07, anchor='n') button1 = Button(lower_frame, text='Select Files', bg='white', fg='black', borderless=0, font=40, command=lambda: addFile(middle_frame)) button1.place(relx=0, relwidth=0.5, relheight=1) button2 = Button(lower_frame, text='Done', bg='white', fg='black', borderless=0, font=40, command=lambda: controller.show_frame("Preprocess")) button2.place(relx=0.5, relwidth=0.5, relheight=1)
def kfcRegular(*args): itemDict = {} #initialization of dictionary to hold store menu information global time_str global day_str #commands to retrive an image from the system which will be used to design the various widgets present in the GUI kfc_back_img = Image.open( "/Users/aneez.jah/Desktop/Y1S1 Coursework/Introduction to Computational Thinking/Mini Project/NSCanteenSystem/Stores/KFC_main.png" ) store_closed_img = Image.open( "/Users/aneez.jah/Desktop/Y1S1 Coursework/Introduction to Computational Thinking/Mini Project/NSCanteenSystem/Stores/KFC_close.png" ) KFC_main = ImageTk.PhotoImage(kfc_back_img) KFC_close = ImageTk.PhotoImage(store_closed_img) #initialization block for the widgets to be displayes to the user. Defines the various widgets and places them at an arbitrary location on the window background_label = Label(root, image=KFC_main) background_label.image = KFC_main # this is to keep a copy of the image in the file calcButton = Button(root, text="Calculate", command=calcWaitTime, image=EnterButton) waittime_result = ttk.Label(root, textvariable=waitTime) qEntry = ttk.Entry(root, textvariable=numPeople) backButton = Button(root, text="", command=curStoresPage, image=back_button) endProg = Button(root, text="", command=leavePage, image=CloseButton) place_widgets(background_label, calcButton, waittime_result, qEntry, backButton, endProg) #the conditional statements retrieve store menu information from text files depending on the present or user defined date and time if (hour_int >= 6 and hour_int <= 10): f = open( "/Users/aneez.jah/Desktop/Y1S1 Coursework/Introduction to Computational Thinking/Mini Project/NSCanteenSystem/kfc_breakfast.txt", "r") elif hour_int >= 11 and hour_int < 22: f = open( "/Users/aneez.jah/Desktop/Y1S1 Coursework/Introduction to Computational Thinking/Mini Project/NSCanteenSystem/kfc_regular.txt", "r") else: KFC_close_label = ttk.Label(root, image=KFC_close) KFC_close_label.place(x=0, y=0, relwidth=1, relheight=1) backButton = Button(root, text="", command=curStoresPage, image=back_button) backButton.place(x=30, y=400, height=50, width=50) endProg = Button(root, text="", command=leavePage, image=CloseButton) endProg.place(x=740, y=20, height=34, width=40) display_menu(f, itemDict) root.bind( '<Return>', calcWaitTime ) #binds the caluclate wait time button to the enter key on the keyboard
def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller canvas = Canvas(self, height=HEIGHT, width=WIDTH) canvas.pack() background_frame = Frame(self, bg="#7ECFEC") background_frame.place(relwidth=1, relheight=1) upper_frame = Frame(self, bg="Black") upper_frame.place(relx=0.5, rely=0.02, relwidth=0.9, relheight=0.07, anchor='n') welcomelabel = Label(upper_frame, text="Welcome!", fg="Black", font=("Modern", 15, "bold")) welcomelabel.place(relwidth=1, relheight=1) middle_frame = Frame(self, bg='Black') middle_frame.place(relx=0.5, rely=0.1, relwidth=0.9, relheight=0.8, anchor='n') textlabel = Label( middle_frame, text= "This GUI will help you to perform LDA Topic Modeling. \n \nFirst you will be asked " "to select your (german) corpus.\n \n After that you can specify the parameters, e.g. the " "number of topics. \n \n \n Click 'Got it' to continue. \n \n Good luck!", bg='white', font=('Modern', 12)) textlabel.place(relwidth=1, relheight=1) lower_frame = Frame(self, bg='Black', bd=5) lower_frame.place(relx=0.5, rely=0.92, relwidth=0.2, relheight=0.07, anchor='n') button = Button(lower_frame, text='Got it!', bg='white', fg='black', borderless=0, font=40, command=lambda: controller.show_frame("ChooseCorpus")) button.place(relx=0, relwidth=1, relheight=1)
def __create_module_button(self, module, window): module_button = Button(window, text=f"{module.module_type}\n({module.id})") module_type = str(module.__class__) if 'output' in module_type: color = "orange" elif 'input' in module_type: color = "purple" else: color = "yellow" module_button.configure(bg=color, command=lambda: self.__change_module(module)) # TODO: Update button position as the module changes its position module_button.place( x=170 + 60 * module.position[0], y=180 - 40 * module.position[1], width=60, height=40, ) # module button list self._modules.append(module_button)
def mainScreen(*args): global flag flag = False style = ttk.Style() #style tag to define the label style and font color style.configure("TLabel", foreground='white') #commands to retrive an image from the system which will be used to design the various widgets present in the GUI main_back_img = Image.open( "/Users/aneez.jah/Desktop/Y1S1 Coursework/Introduction to Computational Thinking/Mini Project/NSCanteenSystem/MainPage/MainBackground.png" ) currStores_button_img = Image.open( "/Users/aneez.jah/Desktop/Y1S1 Coursework/Introduction to Computational Thinking/Mini Project/NSCanteenSystem/MainPage/CurrentStore.png" ) otherDates_button_img = Image.open( "/Users/aneez.jah/Desktop/Y1S1 Coursework/Introduction to Computational Thinking/Mini Project/NSCanteenSystem/MainPage/OtherDates.png" ) image3 = Image.open( "/Users/aneez.jah/Desktop/Y1S1 Coursework/Introduction to Computational Thinking/Mini Project/NSCanteenSystem/MainPage/black.png" ) MainBackground = ImageTk.PhotoImage(main_back_img) CurrentStore = ImageTk.PhotoImage(currStores_button_img) OtherDates = ImageTk.PhotoImage(otherDates_button_img) black_background = ImageTk.PhotoImage(image3) current_time = time_str day = day_str #initialization block for the widgets to be displayes to the user. Defines the various widgets and places them at an arbitrary location on the window background_label = Label(root, image=MainBackground) background_label.image = MainBackground # this is to keep a copy of the image in the file dayLabel = ttk.Label(root, text=day, image=black_background, compound=CENTER) timeLabel = ttk.Label(root, text=current_time, image=black_background, compound=CENTER) currDate = Button(root, text="Current Stores", command=lambda: curStoresPage(), image=CurrentStore) otherDate = Button(root, text="View stores by other dates", command=lambda: dateEntryPage(), image=OtherDates) endProg = Button(root, text="", command=leavePage, image=CloseButton) #placement block for the widgets to be displayed to the user. Defines the coordinates on the window at which each widget should be placed background_label.place(x=0, y=0, relwidth=1, relheight=1) dayLabel.place(x=100, y=20, height=30, width=100) timeLabel.place(x=400, y=20, height=30, width=100) currDate.place(x=252, y=270, height=54, width=292) otherDate.place(x=252, y=350, height=54, width=292) endProg.place(x=740, y=20, height=34, width=40) root.mainloop()
def quit_page(self): self.root.update() rightframe = Frame(self.root, bg=rightframe_background_color) rightframe.pack(side=RIGHT) rightframe.place(height=800, width=800, x=200, y=0) quit_heading = Label(rightframe, text="Quit", font=(standard_font_name, text_font_size, font_weight)) quit_heading.place(x=35, y=20) quit_note = "Pressing Yes button will shut the entirely." quit_heading = Label(rightframe, text=quit_note, font=(standard_font_name, text_font_size, font_weight)) quit_heading.place(x=35, y=50) quit_button = Button(rightframe, text="Yes", fg="black", width=20, command=lambda: quit_program(self)) quit_button.place(x=35, y=100)
def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller canvas = Canvas(self, height=HEIGHT, width=WIDTH) canvas.pack() background_frame = Frame(self, bg="#7ECFEC") background_frame.place(relwidth=1, relheight=1) upper_frame = Frame(self, bg="Black") upper_frame.place(relx=0.5, rely=0.02, relwidth=0.9, relheight=0.07, anchor='n') welcomelabel = Label(upper_frame, text="Start All Over?", fg="Black", font=("Modern", 15, "bold")) welcomelabel.place(relwidth=1, relheight=1) middle_frame = Frame(self, bg='White') middle_frame.place(relx=0.5, rely=0.1, relwidth=0.9, relheight=0.8, anchor='n') textlabel = Label( middle_frame, text="Do you want to use a new corpus?\n For this you " "have to delete your saved data. \nYou will then have to select a new corpus " "and \ndo preprocessing again.", bg='white', font=('Modern', 15)) textlabel.place(rely=0.08, relwidth=1, relheight=0.8) textlabel2 = Label(middle_frame, text="Do you want to try new parameters?", bg='white', font=('Modern', 15)) textlabel2.place(rely=0.05, relwidth=1, relheight=0.15) buttonparams = Button( middle_frame, text='Try different parameters', bg='white', fg='black', borderless=0, font=40, command=lambda: controller.show_frame("SelectParams")) buttonparams.place(relx=0.3, rely=0.2, relwidth=0.4, relheight=0.1) button = Button(middle_frame, text="Delete saved data", bg='#ff4d4d', fg='black', borderless=0, font=40, command=lambda: delete()) button.place(relx=0.35, rely=0.62, relwidth=0.3, relheight=0.2) buttoncorpus = Button( middle_frame, text='Choose New Corpus', bg='white', fg='black', borderless=0, font=40, command=lambda: controller.show_frame("ChooseCorpus")) buttoncorpus.place(relx=0.3, rely=0.85, relwidth=0.4, relheight=0.1) lower_frame = Frame(self, bg='Black', bd=5) lower_frame.place(relx=0.5, rely=0.92, relwidth=0.5, relheight=0.07, anchor='n') button1 = Button(lower_frame, text='Go Back', bg='white', fg='black', borderless=0, font=40, command=lambda: controller.show_frame("ShowTopics")) button1.place(relx=0, relwidth=0.5, relheight=1) button2 = Button(lower_frame, text='Quit Program', bg='white', fg='black', borderless=0, font=40, command=lambda: quit()) button2.place(relx=0.5, relwidth=0.5, relheight=1)
def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller canvas = Canvas(self, height=HEIGHT, width=WIDTH) canvas.pack() background_frame = Frame(self, bg="#7ECFEC") background_frame.place(relwidth=1, relheight=1) upper_frame = Frame(self, bg="Black") upper_frame.place(relx=0.5, rely=0.02, relwidth=0.9, relheight=0.07, anchor='n') welcomelabel = Label(upper_frame, text="Topics", fg="Black", font=("Modern", 15, "bold")) welcomelabel.place(relwidth=1, relheight=1) middle_frame = Frame(self, bg='White') middle_frame.place(relx=0.5, rely=0.1, relwidth=0.9, relheight=0.8, anchor='n') textlabel = Label( middle_frame, text= "You can click here to view your topics, \nthis will open the visualization" " in your browser. \n If this does not work, please check your version " "of PyLDAvis.", bg='white', font=('Modern', 15)) textlabel.place(relwidth=1, relheight=0.8) button = Button(middle_frame, text="Show Topics", bg='#7ECFEC', fg='black', borderless=0, font=40, command=lambda: visualize()) button.place(relx=0.3, rely=0.6, relwidth=0.4, relheight=0.3) lower_frame = Frame(self, bg='Black', bd=5) lower_frame.place(relx=0.5, rely=0.92, relwidth=0.5, relheight=0.07, anchor='n') button1 = Button(lower_frame, text='Go Back', bg='white', fg='black', borderless=0, font=40, command=lambda: controller.show_frame("SelectParams")) button1.place(relx=0, relwidth=0.5, relheight=1) button2 = Button(lower_frame, text='Start all over?', bg='white', fg='black', borderless=0, font=40, command=lambda: controller.show_frame("End")) button2.place(relx=0.5, relwidth=0.5, relheight=1)
def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller canvas = Canvas(self, height=HEIGHT, width=WIDTH) canvas.pack() background_frame = Frame(self, bg="#7ECFEC") background_frame.place(relwidth=1, relheight=1) upper_frame = Frame(self, bg="Black") upper_frame.place(relx=0.5, rely=0.02, relwidth=0.9, relheight=0.07, anchor='n') welcomelabel = Label(upper_frame, text="Parameters", fg="Black", font=("Modern", 15, "bold")) welcomelabel.place(relwidth=1, relheight=1) middle_frame = Frame(self, bg='White') middle_frame.place(relx=0.5, rely=0.1, relwidth=0.9, relheight=0.8, anchor='n') label = Label( middle_frame, text= "Select your parameters and click 'Run the model'. \n No_above needs to be a float" " between 0 and 1. \n The other parameters should be integers. ") label.place(rely=0.05, relwidth=1, relheight=0.2) label1 = Label(middle_frame, text="Number of Topics:") label1.place(rely=0.25, relwidth=0.5, relheight=0.1) entry1 = Entry(middle_frame) entry1.place(relx=0.5, rely=0.25, relwidth=0.3, relheight=0.1) entry1.insert(END, '10') entry1.place(relx=0.5, rely=0.25, relwidth=0.3, relheight=0.1) label2 = Label(middle_frame, text="No Below:") label2.place(rely=0.35, relwidth=0.5, relheight=0.1) entry2 = Entry(middle_frame) entry2.place(relx=0.5, rely=0.35, relwidth=0.3, relheight=0.1) entry2.insert(END, '2') entry2.place(relx=0.5, rely=0.35, relwidth=0.3, relheight=0.1) label3 = Label(middle_frame, text="No Above:") label3.place(rely=0.45, relwidth=0.5, relheight=0.1) entry3 = Entry(middle_frame) entry3.place(relx=0.5, rely=0.45, relwidth=0.3, relheight=0.1) entry3.insert(END, '0.5') entry3.place(relx=0.5, rely=0.45, relwidth=0.3, relheight=0.1) label4 = Label(middle_frame, text="Chunk Size:") label4.place(rely=0.55, relwidth=0.5, relheight=0.1) entry4 = Entry(middle_frame) entry4.place(relx=0.5, rely=0.55, relwidth=0.3, relheight=0.1) entry4.insert(END, '2000') entry4.place(relx=0.5, rely=0.55, relwidth=0.3, relheight=0.1) label5 = Label(middle_frame, text="Passes:") label5.place(rely=0.65, relwidth=0.5, relheight=0.1) entry5 = Entry(middle_frame) entry5.place(relx=0.5, rely=0.65, relwidth=0.3, relheight=0.1) entry5.insert(END, '20') entry5.place(relx=0.5, rely=0.65, relwidth=0.3, relheight=0.1) label6 = Label(middle_frame, text="Iterations:") label6.place(rely=0.75, relwidth=0.5, relheight=0.1) entry6 = Entry(middle_frame) entry6.place(relx=0.5, rely=0.75, relwidth=0.3, relheight=0.1) entry6.insert(END, '400') entry6.place(relx=0.5, rely=0.75, relwidth=0.3, relheight=0.1) low_frame = Frame(self, bg='White', bd=5) low_frame.place(relx=0.5, rely=0.8, relwidth=0.3, relheight=0.07, anchor='n') button = Button( low_frame, text='Run the model', bg='#7ECFEC', fg='black', borderless=0, font=40, command=lambda: run_tm(entry1.get(), entry2.get(), entry3.get(), entry4.get(), entry5.get(), entry6.get())) button.place(relwidth=1, relheight=1) lower_frame = Frame(self, bg='Black', bd=5) lower_frame.place(relx=0.5, rely=0.92, relwidth=0.5, relheight=0.07, anchor='n') button1 = Button(lower_frame, text='Go Back', bg='white', fg='black', borderless=0, font=40, command=lambda: controller.show_frame("Preprocess")) button1.place(relx=0, relwidth=0.5, relheight=1) button2 = Button(lower_frame, text='Done', bg='white', fg='black', borderless=0, font=40, command=lambda: controller.show_frame("ShowTopics")) button2.place(relx=0.5, relwidth=0.5, relheight=1)
def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller canvas = Canvas(self, height=HEIGHT, width=WIDTH) canvas.pack() background_frame = Frame(self, bg="#7ECFEC") background_frame.place(relwidth=1, relheight=1) upper_frame = Frame(self, bg="Black") upper_frame.place(relx=0.5, rely=0.02, relwidth=0.9, relheight=0.07, anchor='n') welcomelabel = Label(upper_frame, text="Preprocessing", fg="Black", font=("Modern", 15, "bold")) welcomelabel.place(relwidth=1, relheight=1) middle_frame = Frame(self, bg='White') middle_frame.place(relx=0.5, rely=0.1, relwidth=0.9, relheight=0.8, anchor='n') label1 = Label( middle_frame, text= "You can now preprocess your selected data.\n \n If this is your first time " "preprocessing,\n this might take some time.\n \n Otherwise your saved data " "will be loaded. \n If this is the case, you can skip this step.") label1.place(relx=0., rely=0.1, relwidth=1, relheight=0.5) button = Button(middle_frame, text="Click here to preprocess", bg='#7ECFEC', fg='black', borderless=0, font=40, command=lambda: preprocess("./save.txt")) button.place(relx=0.1, rely=0.7, relwidth=0.8, relheight=0.2) lower_frame = Frame(self, bg='Black', bd=5) lower_frame.place(relx=0.5, rely=0.92, relwidth=0.5, relheight=0.07, anchor='n') button1 = Button(lower_frame, text='Go Back', bg='white', fg='black', borderless=0, font=40, command=lambda: controller.show_frame("ChooseCorpus")) button1.place(relx=0, relwidth=0.5, relheight=1) button2 = Button(lower_frame, text='Done', bg='white', fg='black', borderless=0, font=40, command=lambda: controller.show_frame("SelectParams")) button2.place(relx=0.5, relwidth=0.5, relheight=1)
def __init__(self, master, state): self.master = master master.title(state) self.main_frame = tk.Frame(self.master, height=HEIGHT, width=WIDTH) self.main_frame.pack() self.current_mod = tk.StringVar() self.current_mod.set('Current Module:') self.comp_stat = tk.StringVar() self.comp_stat.set("Completion Status: 10/100") fontStyle = tkFont.Font(family="Lucida Grande", size=20) db_title = tk.Label(self.main_frame, text="Dashboard Activity", font=fontStyle, bg='white', fg=DARK_PURPLE) db_title.place(anchor='n', relx=0.4, rely=0.05) name_frame = tk.Frame(self.main_frame, bg='#8AA29E') name_frame.place(relx=0.15, rely=0, relwidth=0.3, relheight=0.1, anchor='n') name = tk.Label(name_frame, text="Company Name", font=fontStyle, bg='#8AA29E', fg='white') name.place(relx=0.2, rely=0.1) self.module_list_frame = tk.Frame(self.main_frame, bg=MING) self.module_list_frame.place(relx=0.15, rely=0.1, relwidth=0.3, relheight=1, anchor='n') scrollbar = tk.Scrollbar(self.module_list_frame) scrollbar.pack(side=tk.RIGHT, fill=tk.Y) # scrollbar.place(relx=0.1, rely=0.2) self.mylist = tk.Listbox(self.module_list_frame, borderwidth=0, yscrollcommand=scrollbar.set, width=WIDTH, height=HEIGHT, font=fontStyle, bg=MING, fg='white') i = 0 for mod in MODULES: self.mylist.insert(tk.END, mod) if i > 5: self.mylist.itemconfig(i, fg="gray") i = i + 1 self.mylist.pack(padx=10, pady=10, fill="both", expand=True) # self.mylist.place(relx=0.1, rely=0.3) scrollbar.config(command=self.mylist.yview) self.mylist.bind( '<<ListboxSelect>>', self.click_button) # basically list box on click listener # self.disable_item(1) # statistics frames self.box1 = tk.Frame(self.main_frame, bg=CHAMPAGNE) self.box1.place(relx=0.385, rely=0.2, width=150, height=130, anchor='n') self.box2 = tk.Frame(self.main_frame, bg=MING) self.box2.place(relx=0.55, rely=0.2, width=150, height=130, anchor='n') self.box3 = tk.Frame(self.main_frame, bg=LIGHT_GRAY) self.box3.place(relx=0.725, rely=0.2, width=150, height=130, anchor='n') self.box4 = tk.Frame(self.main_frame, bg=DARK_PURPLE) self.box4.place(relx=0.9, rely=0.2, width=150, height=130, anchor='n') self.set_stats() self.your_mod_frame = tk.Frame(self.main_frame, bg=DESSERT_SAND) self.your_mod_frame.place(relx=0.64, rely=0.5, relwidth=0.66, relheight=0.3, anchor='n') self.your_mod_label = tk.Label(self.your_mod_frame, textvariable=self.current_mod, font=fontStyle, bg=DESSERT_SAND) self.your_mod_label.place(relx=0.05, rely=0.1) self.completion_label = tk.Label(self.your_mod_frame, textvariable=self.comp_stat, bg=DESSERT_SAND) self.completion_label.place(relx=0.05, rely=0.4) self.start_sess_btn = tk.Button(self.main_frame, text="Start Session", command=self.start_session) self.start_sess_btn.place(relx=0.5, rely=0.9) self.start_sess_btn["state"] = tk.DISABLED start_sess_btn = tk.Button(self.main_frame, text="View Session Reports") start_sess_btn.place(relx=0.7, rely=0.9) profile_btn = Button(self.main_frame, text="View Profile", bg=LIGHT_GRAY, fg='black', borderless=1) profile_btn.place(relx=0.87, rely=0.05) self.value = ""
class Quiz: def __init__(self, master): self.master = master master.title("Quiz") self.main_frame = tk.Frame(self.master, height=HEIGHT, width=WIDTH, bg='white', borderwidth=1) self.main_frame.pack() self.module_list_frame = tk.Frame(self.main_frame, bg=LIGHT_GRAY) self.module_list_frame.place(relx=0.1, rely=0, relwidth=0.2, relheight=1, anchor='n') scrollbar = tk.Scrollbar(self.module_list_frame) scrollbar.pack(side=tk.RIGHT, fill=tk.Y) question_list_font = tkFont.Font(family="Lucida Grande", size=16) self.mylist = tk.Listbox(self.module_list_frame, borderwidth=0, yscrollcommand=scrollbar.set, width=WIDTH, height=HEIGHT, font=question_list_font, bg=LIGHT_GRAY, fg='white') question_header_font = tkFont.Font(family="Lucida Grande", size=18) question_label = tk.Label(self.module_list_frame, text="Question List".upper(), font=question_header_font, bg=LIGHT_GRAY, fg='white') question_label.pack() i = 1 while i <= 20: self.mylist.insert(tk.END, "Question: " + str(i)) i = i + 1 self.mylist.pack(padx=10, pady=10, fill="both", expand=True) scrollbar.config(command=self.mylist.yview) self.current_question = "" self.mylist.bind( '<<ListboxSelect>>', self.click_button) # basically list box on click listener self.header_font = tkFont.Font(family="Lucida Grande", size=48) self.header = tk.Label(self.main_frame, text="Quiz", fg=MING, font=self.header_font) self.header.place(relx=0.55, rely=0.1, anchor='center') self.inst_frame = tk.Frame(self.main_frame, bg=CHAMPAGNE, highlightbackground='black', highlightthickness=6) self.inst_frame.place(relx=0.25, rely=0.25, relheight=0.5, relwidth=0.65) instructions_font = tkFont.Font(family="Lucida Grande", size=18) instructions = tk.Label( self.inst_frame, text= "There are 20 questions on this quiz.\nYou will be given a word which you will have to " "\nspeak out loud to be graded", font=instructions_font, fg=DARK_PURPLE, bg=CHAMPAGNE) instructions.place(relx=0.5, rely=0.5, anchor='center') self.start_quiz = Button(self.inst_frame, text="Start Quiz", bg=MING, fg='white', borderless=1, command=self.start_quiz) self.start_quiz.place(relx=0.5, rely=0.8, anchor='center') filename = G_USERNAME + ".txt" self.question_bank = get_vowel_quiz(get_value_from_line(filename, 5)) self.question_var = tk.StringVar() for i in self.question_bank: print(i[2]) # display the clicked location def click_button(self, event): w = event.widget index = int(w.curselection()[0]) self.current_question = w.get(index) self.current_question = self.current_question.split(": ")[1] string = self.question_bank[int(self.current_question)][2] self.question_var.set(string) def start_quiz(self): self.inst_frame.destroy() self.header.destroy() self.question_frame = tk.Frame(self.main_frame, bg=MING) self.question_frame.place(relx=0.55, rely=0.3, anchor='center', relheight=0.3, relwidth=0.55) self.current_question = 1 self.question_var.set((self.question_bank[self.current_question][2])) self.user_question = tk.Label(self.question_frame, textvariable=self.question_var, bg=MING, fg='white', font=self.header_font) self.user_question.place(relx=0.5, rely=0.3, anchor='center') self.user_answer_txt = tk.StringVar() self.user_answer_txt.set("You said: ") self.answer_frame = tk.Frame(self.main_frame, bg=CHAMPAGNE) self.answer_frame.place(relx=0.55, rely=0.6, anchor='center', relheight=0.3, relwidth=0.55) self.user_answer_label = tk.Label(self.answer_frame, textvariable=self.user_answer_txt, bg=CHAMPAGNE, fg=DARK_PURPLE) self.user_answer_label.place(relx=0.5, rely=0.5, anchor='center') self.record_btn = tk.Button(self.main_frame, text="Record", bg=DARK_CYAN, fg='white', command=self.record) self.record_btn.place(relx=0.4, rely=0.8) self.listen_btn = tk.Button(self.main_frame, text="Listen", command=self.listen) self.listen_btn.place(relx=0.6, rely=0.8) def record(self): try: self.captured_text = capture().lower() self.user_answer_txt.set("You said: " + self.captured_text) except Exception: print("Error") def listen(self): speak(self.user_answer_txt.get())
def curStoresPage(*args): global flag if flag == False: SetDateToCurr() else: pass #commands to retrieve an image from the system which will be used to design the various widgets present in the GUI availableStores_back_img = Image.open( "/Users/aneez.jah/Desktop/Y1S1 Coursework/Introduction to Computational Thinking/Mini Project/NSCanteenSystem/CurrStores/AvailStores.png" ) kfc_button_img = Image.open( "/Users/aneez.jah/Desktop/Y1S1 Coursework/Introduction to Computational Thinking/Mini Project/NSCanteenSystem/CurrStores/KFC.png" ) McD_button_img = Image.open( "/Users/aneez.jah/Desktop/Y1S1 Coursework/Introduction to Computational Thinking/Mini Project/NSCanteenSystem/CurrStores/McD.png" ) noodles_button_img = Image.open( "/Users/aneez.jah/Desktop/Y1S1 Coursework/Introduction to Computational Thinking/Mini Project/NSCanteenSystem/CurrStores/Noodles.png" ) western_button_img = Image.open( "/Users/aneez.jah/Desktop/Y1S1 Coursework/Introduction to Computational Thinking/Mini Project/NSCanteenSystem/CurrStores/Western.png" ) miniwok_button_img = Image.open( "/Users/aneez.jah/Desktop/Y1S1 Coursework/Introduction to Computational Thinking/Mini Project/NSCanteenSystem/CurrStores/Miniwok.png" ) AvailStores = ImageTk.PhotoImage(availableStores_back_img) KFC = ImageTk.PhotoImage(kfc_button_img) McD = ImageTk.PhotoImage(McD_button_img) Noodles = ImageTk.PhotoImage(noodles_button_img) PorkChop = ImageTk.PhotoImage(western_button_img) Miniwok = ImageTk.PhotoImage(miniwok_button_img) style = ttk.Style() #style tag to define the label style and font color style.configure("TLabel", foreground='black') background_label = Label(root, image=AvailStores) background_label.image = AvailStores # this is to keep a copy of the image in the file store1 = Button(root, text="KFC", command=kfcRegular, image=KFC) store2 = Button(root, text="McDonald's", command=McDRegular, image=McD) store3 = Button(root, text="Mini Wok", command=Chinese, image=Miniwok) store4 = Button(root, text="Noodle", command=Noodle, image=Noodles) store5 = Button(root, text="Western", command=Western, image=PorkChop) backButton = Button(root, text="", command=mainScreen, image=back_button) endProg = Button(root, text="", command=leavePage, image=CloseButton) #placement block for the widgets to be displayed to the user. Defines the coordinates on the window at which each widget should be placed background_label.place(x=0, y=0, relwidth=1, relheight=1) store1.place(x=350, y=175, height=46, width=190) store2.place(x=350, y=230, height=46, width=190) store3.place(x=350, y=405, height=46, width=190) store4.place(x=350, y=290, height=46, width=190) store5.place(x=350, y=348, height=46, width=190) backButton.place(x=30, y=400, height=50, width=50) endProg.place(x=740, y=20, height=34, width=40)
def createWidgets(self): self.title("嗖音HOME " + self.version[1:] + " - 独居者") if sys.platform[:3] == "win": self.iconbitmap("logo.ico") self.attributes("-alpha", 0.99) # 设置颜色 progress_color = "#1E94A0" progress_chunk_color = "#FA7268" declare_color = "red" update_color = "#F9425B" update_bg_color = "#0071CF" font_color = "#EBE5D9" btn_color = "#14B09B" frame_color = "#0359AE" # 设置字体 if sys.platform[:3] == "win": l_font = ("宋体", 12) m_font = ("宋体", 11) s_font = ("宋体", 9) if sys.platform == "darwin": l_font = ("宋体", 16) m_font = ("宋体", 15) s_font = ("宋体", 12) # 设置窗口大小 width = 603 height = 339 # 获取屏幕尺寸以计算布局参数,使窗口居于屏幕中央 screenwidth = self.winfo_screenwidth() screenheight = self.winfo_screenheight() geometry_str = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 3) self.geometry(geometry_str) self.resizable(width=False, height=False) L_frame = tk.Frame(width=373, height=height, bg=frame_color) R_frame = tk.Frame(width=230, height=height, bg=frame_color) L_frame.grid(row=0, column=0) R_frame.grid(row=0, column=1) self.update_info.set("检测更新中......") # 创建 t = threading.Thread(target=self.update_fun) read_t = threading.Thread(target=self.read_fun) # 守护 !!! t.setDaemon(True) read_t.setDaemon(True) # 启动 t.start() read_t.start() # 右边开始布局 updateLab = tk.Label(R_frame, textvariable=self.update_info, font=l_font, bg=update_bg_color, fg=update_color) updateLab.place(x=0, y=0, width=230, height=25) updateLab.bind("<Button-1>", self.open_browser) if sys.platform[:3] == "win": self.text = tk.Text(R_frame, width=5, height=5, bd=1, relief="solid", font=s_font, bg=frame_color, fg=font_color) if sys.platform == "darwin": self.text = tk.Text(R_frame, width=5, height=5, bd=1, relief="solid", font=s_font, bg=frame_color, fg=font_color, highlightthickness=0) self.text.place(x=30, y=50, width=170, height=155) self.text.insert(tk.INSERT, "有什么想对开发者说的可以说") self.text.bind("<Button-1>", self.del_show) if sys.platform[:3] == "win": buttonSend = tk.Button(R_frame, text="给开发者的话", command=self.send_message, font=m_font, bd=0, bg=btn_color, fg=font_color, activeforeground=font_color, activebackground=frame_color) if sys.platform == "darwin": buttonSend = Button(R_frame, text="给开发者的话", command=self.send_message, font=m_font, borderless=1, bg=btn_color, fg=font_color, activeforeground=font_color, activebackground=frame_color) buttonSend.place(x=65, y=230, width=101, height=30) declare_str = "声明:仅供个人录制音频转换使用" labDeclare = tk.Label(R_frame, text=declare_str, wraplength=151, justify="left", font=s_font, bd=1, relief="solid", bg=frame_color, fg=declare_color) labDeclare.place(x=40, y=282, width=151, height=41) # 左边开始布局 self.read_str.set("随机阅读:正在加载中......") labShow = tk.Label(L_frame, textvariable=self.read_str, wraplength=252, justify="left", anchor="w", padx=5, bd=1, relief="solid", bg=frame_color, fg=font_color) labShow.place(x=30, y=25, width=313, height=70) labReadAll = tk.Label(L_frame, text="查看全文", bg=frame_color, fg="#22B14C") labReadAll.place(x=287, y=26, width=55, height=68) labReadAll.bind("<Button-1>", self.read_page) self.content.set("请选择要转换的音频文件") lab = tk.Label(L_frame, textvariable=self.content, font=m_font, bg=frame_color, fg=font_color) lab.place(x=30, y=110, width=313, height=20) if sys.platform[:3] == "win": self.entry_url = tk.Entry(L_frame, validate="focusin", validatecommand=self.del_url_show, font=s_font, bd=1, relief="solid", bg=frame_color, fg=font_color) if sys.platform == "darwin": self.entry_url = tk.Entry(L_frame, validate="focusin", validatecommand=self.del_url_show, font=s_font, bd=1, relief="solid", bg=frame_color, fg=font_color, highlightthickness=0) self.entry_url.place(x=30, y=160, width=238, height=30) self.entry_url.insert(0, "请输入分享链接即可") if sys.platform[:3] == "win": self.buttonOpenUrl = tk.Button(L_frame, text="网络转换", command=self.urlfile_convert, font=m_font, bd=0, bg=btn_color, fg=font_color, activeforeground=font_color, activebackground=frame_color) if sys.platform == "darwin": self.buttonOpenUrl = Button(L_frame, text="网络转换", command=self.urlfile_convert, font=m_font, borderless=1, bg=btn_color, fg=font_color, activeforeground=font_color, activebackground=frame_color) self.buttonOpenUrl.place(x=268, y=160, width=75, height=30) if sys.platform[:3] == "win": self.buttonStart = tk.Button(L_frame, text="本地转换", command=self.localfile_convert, font=m_font, bd=0, bg=btn_color, fg=font_color, activeforeground=font_color, activebackground=frame_color) if sys.platform == "darwin": self.buttonStart = Button(L_frame, text="本地转换", command=self.localfile_convert, font=m_font, borderless=1, bg=btn_color, fg=font_color, activeforeground=font_color, activebackground=frame_color) self.buttonStart.place(x=268, y=200, width=75, height=30) if sys.platform[:3] == "win": buttonOpen = tk.Button(L_frame, text="打开本地文件", command=self.openfile, font=m_font, bd=0, bg=btn_color, fg=font_color, activeforeground=font_color, activebackground=frame_color) if sys.platform == "darwin": buttonOpen = Button(L_frame, text="打开本地文件", command=self.openfile, font=m_font, borderless=1, bg=btn_color, fg=font_color, activeforeground=font_color, activebackground=frame_color) buttonOpen.place(x=110, y=200, width=101, height=30) labOut = tk.Label(L_frame, text="输出配置:", justify="left", font=m_font, bg=frame_color, fg=font_color) labOut.place(x=30, y=250, width=75, height=30) buttonVer = tk.Checkbutton(L_frame, text="旧版", font=m_font, variable=self.sampling_rate_ver, bg=frame_color, fg=font_color, activeforeground=font_color, activebackground=frame_color, selectcolor=frame_color) buttonVer.place(x=110, y=250, width=71, height=30) if sys.platform[:3] == "win": buttonFile = tk.Button(L_frame, text="浏览输出", command=show_file_path, font=s_font, bd=0, bg=btn_color, fg=font_color, activeforeground=font_color, activebackground=frame_color) if sys.platform == "darwin": buttonFile = Button(L_frame, text="浏览输出", command=show_file_path, font=s_font, borderless=1, bg=btn_color, fg=font_color, activeforeground=font_color, activebackground=frame_color) buttonFile.place(x=268, y=291, width=75, height=23) labHelp = tk.Label(L_frame, text="<使用指南>", font=s_font, bg=frame_color, fg=font_color) labHelp.place(x=10, y=306, width=75, height=23) labHelp.bind("<Button-1>", self.show_help) progressbar_style = ttk.Style() progressbar_style.theme_use('alt') progressbar_style.configure("blue.Vertical.TProgressbar", troughcolor=progress_color, background=progress_chunk_color, troughrelief="flat") self.progressBar = ttk.Progressbar(self, style="blue.Vertical.TProgressbar", length=115, mode="determinate", orient="vertical") self.progressBar.place(x=368, y=0, width=5, height=height)
return value # Place Logo and title TODO! Doesnt work! Removed to minimize executable size # logo = Image.open('./cal.jpeg') # seems to only work with jpg # tklogo = ImageTk.PhotoImage(logo) # size = logo.size # title.create_image(30, 30, anchor='center', image=tklogo) # removed logo for aesthetic purposes var = tk.StringVar() label = tk.Label(title, textvariable=var, bg=YELLOW) var.set("Schtoics") label.pack() # select file button TODO: if windows use tk.Button button = Button(frame, text="choose\n file", padx=10, pady=1, bg=YELLOW, fg=BLUE, borderless=1, highlightthickness=0, activebackground='#fa0', activeforeground='black', command=getFile) button.place(relx=0.3, rely=0.4, relheight=0.3, relwidth=0.42) year = tk.StringVar(frame) quarter = tk.StringVar(frame) # default value year.set("2020") quarter.set("1") #TODO: get based on the system current date and times. also autogenerate the years options based on date. dropdownFont = tk.font.Font(family="Myriad Pro", size=20) yearDropdown = tk.OptionMenu(frame, year, "2020", "2021", "2022") yearDropdown.config(bg = BLUE, width=20, font=dropdownFont) menu = root.nametowidget(yearDropdown.menuname) menu.config(font=dropdownFont) yearDropdown.place(relx=0.6, rely=0.12, relwidth=0.3) quarterDropdown = tk.OptionMenu(frame, quarter, "1", "2", "3")
def run(self): width, height = 910, 750 window = Tk() window.title(f"GUI Debugger for PyMODI (v{modi.__version__})") window.geometry(f"{width}x{height}") window.resizable(False, False) canvas = Canvas(window, width=width, height=height) canvas.create_rectangle(10, 40, 410, 340, outline='black') canvas.pack() # cmd (ins) field Label(window, text='c:').place(x=10, y=5) self.__cmd = Entry(window) self.__cmd.place(x=25, y=5, width=40) # sid field Label(window, text='s:').place(x=70, y=5) self.__sid = Entry(window) self.__sid.place(x=85, y=5, width=40) # did field Label(window, text='d:').place(x=130, y=5) self.__did = Entry(window) self.__did.place(x=145, y=5, width=40) # data field Label(window, text='b:').place(x=190, y=5) self.__data = Entry(window) self.__data.place(x=205, y=5, width=250) generate_button = Button(window, text="Generate", command=self.__parse) generate_button.place(x=455, y=5) # send field Label(window, text='msg:').place(x=545, y=5) self.__input_box = Entry(window) self.__input_box.place(x=580, y=5, width=250) send_button = Button(window, text="Send", command=self.send) send_button.place(x=830, y=5) # TODO: Remove this __query related functions Label(window, text="Filter by Command: ").place(x=420, y=35) self.__query = Entry(window) self.__query.place(x=545, y=33, width=35) Button(window, text="Filter", command=self.__change_query).place(x=580, y=32) # log box (where MODI json messages are shown) self.__log = ScrolledText(window, wrap=WORD, font=('Helvetica', 12)) self.__log.place(x=420, y=60, width=480, height=700) # spec box (where module information are shown) self.__spec = Label(window, text=f"Running PyMODI (v{modi.__version__})", bg='white', anchor=NW, justify='left', font=('Helvetica', 15)) self.__spec.place(x=10, y=350, width=400, height=390) # generate module button in the canvas for module in self.bundle.modules: self.__create_module_button(module, window) # run mainloop while True: try: window.update() self.__append_log() if self.__curr_module: self.__change_spec(self.__curr_module) except TclError: break time.sleep(0.1)
def __init__(self, master, clicked_mod): self.master = master master.title("Learning Characters") self.main_frame = tk.Frame(self.master, height=HEIGHT, width=WIDTH, bg='white', borderwidth=1) self.main_frame.pack() print(clicked_mod) self.training_set = [] if clicked_mod == "Learn Vowels": self.training_set = VOWELS elif clicked_mod == "Learn Consonants": self.training_set = CONSONANTS else: self.training_set = MODIFIERS print(self.training_set) topborder = tk.Frame(self.main_frame, bg=CHAMPAGNE) topborder.place(relx=0, rely=0, relwidth=1, relheight=0.07) self.fontStyle = tkFont.Font(family="Lucida Grande", size=24) header = tk.Label(topborder, text=clicked_mod.upper(), fg='white', font=self.fontStyle, bg=CHAMPAGNE) header.place(relx=0.05, rely=0.2) instructions = tk.Label( self.main_frame, text= "On the left is the example character.\nPractice writing it on the right.", fg=DESSERT_SAND) instructions.place(relx=0.4, rely=0.1) back = tk.Button(self.main_frame, text="<-", command=self.go_back) back.place(relx=0.05, rely=0.1) self.current_char = tk.StringVar() self.current_char.set( str(self.training_set[0]) + " [" + get_pronunciation(self.training_set[0]) + "]") self.character_frame = tk.Frame(self.main_frame, bg=MING, highlightthickness=6, highlightbackground="black") self.character_frame.place(relx=0.25, rely=0.2, width=400, height=190, anchor='n') char_font = tkFont.Font(family="Lucida Grande", size=90) self.char_label = tk.Label(self.character_frame, textvariable=self.current_char, font=char_font, bg=MING, fg='white') self.char_label.place(relx=0.5, rely=0.5, anchor='center') hear_char = Button(self.character_frame, text="Hear", bg=MING, fg='white', command=self.get_char_sound, borderless=1) hear_char.place(relx=0.5, rely=0.1, anchor='n') self.canvas_frame = tk.Frame(self.main_frame, bg=DARK_CYAN, width=420, height=190, highlightthickness=6, highlightbackground="black") self.canvas_frame.place(relx=0.75, rely=0.2, anchor='n') self.practice_canvas = tk.Canvas(self.canvas_frame, bg=CHAMPAGNE, width=275, height=150) self.practice_canvas.place(relx=0.05, rely=0.08) self.image1 = Image.new('RGB', (275, 150), 'white') self.draw = ImageDraw.Draw(self.image1) self.practice_canvas.bind('<1>', self.activate_paint) self.old_x = None self.old_y = None clear_btn = Button(self.canvas_frame, text='Clear', command=self.clear, borderless=1) clear_btn.place(relx=0.85, rely=0.3, anchor='n') btn_save = Button(self.canvas_frame, text='Save', command=self.save, borderless=1) btn_save.place(relx=0.85, rely=0.5, anchor='n') self.example_frame = tk.Frame(self.main_frame, bg=LIGHT_GRAY) self.example_frame.place(relx=0.05, rely=0.6, relheight=0.25, relwidth=0.92) self.current_word = tk.StringVar() self.return_val = get_word_with_same_char(self.training_set[0]) print(self.return_val) if self.return_val != "No Example Available": try: self.current_word.set(self.return_val[0] + " : " + self.return_val[1] + "\n" + get_pronunciation(self.return_val[0])) except TypeError: self.current_word.set(self.return_val[0][0] + " : " + self.return_val[0][1] + "\n" + get_pronunciation(self.return_val[0][0])) else: self.current_word.set(self.return_val) word_example_font = tkFont.Font(family="Lucida Grande", size=30) self.current_word_label = tk.Label(self.example_frame, textvariable=self.current_word, font=word_example_font, bg=LIGHT_GRAY, fg='white') self.current_word_label.place(relx=0.5, rely=0.5, anchor='center') hear_word = Button(self.example_frame, text="Listen Word", bg=LIGHT_GRAY, fg='white', command=self.get_word_sound) hear_word.place(relx=0.1, rely=0.7, anchor='center') bottomborder = tk.Frame(self.main_frame, bg=CHAMPAGNE) bottomborder.place(relx=0, rely=0.93, relwidth=1, relheight=0.07) self.back_btn = Button(bottomborder, text="Previous", bg='white', fg='black', borderless=1, command=self.prev) self.back_btn.place(relx=0.05, rely=0.2) self.next_btn = Button(bottomborder, text="Next", bg='white', fg='black', borderless=1, command=self.next) self.next_btn.place(relx=0.9, rely=0.2) self.index = 0
text="00:00", fill="white", font=(FONT_NAME, 100, "bold")) status_text = canvas.create_text(226, 75, text="TIMER", fill=ORANGE, font=(FONT_NAME, 25, "bold")) check_mark = canvas.create_text(226, 185, fill=GREEN, font=(FONT_NAME, 30, "bold")) canvas.place(x=0, y=0) button = Button(text="START", font=(FONT_NAME, 20, "bold"), bg=GREEN, fg="white", command=start_timer, borderless=0) button.place(x=85, y=200) button = Button(text="RESET", font=(FONT_NAME, 20, "bold"), bg=RED, fg="white", borderless=0, command=reset_timer) button.place(x=265, y=200) window.mainloop()
def show_sign_up_frame(self): self.entering_frame.destroy() signup_frame = tk.Frame(self.master, bg=DARK_CYAN) signup_frame.place(relx=0.5, rely=0.25, relwidth=0.45, relheight=0.6, anchor='n') fontStyle = tkFont.Font(family="Lucida Grande", size=45) # Main header header = tk.Label(self.master, text="MALAYALAM SCHOOL", bg=CHAMPAGNE, fg=DARK_PURPLE, font=fontStyle) header.place(anchor='n', relx=0.5, rely=0.1) # Welcome label welcome_label = tk.Label(signup_frame, text="Welcome!\nPlease Login or Sign Up", bg=DARK_CYAN, fg='white') welcome_label.place(anchor='n', relx=0.5, rely=0.1) # First Name fname_label = tk.Label(signup_frame, text="FIRST NAME", bg=DARK_CYAN, fg='white') fname_label.place(anchor='n', relx=0.25, rely=0.3) self.fname_entry = tk.Entry(signup_frame) self.fname_entry.place(anchor='n', relx=0.7, rely=0.3) # Last Name lname_label = tk.Label(signup_frame, text="LAST NAME", bg=DARK_CYAN, fg='white') lname_label.place(anchor='n', relx=0.25, rely=0.45) self.lname_entry = tk.Entry(signup_frame) self.lname_entry.place(anchor='n', relx=0.7, rely=0.45) # Username widgets username_label = tk.Label(signup_frame, text="USERNAME", bg=DARK_CYAN, fg='white') username_label.place(anchor='n', relx=0.25, rely=0.6) self.username_entry = tk.Entry(signup_frame) self.username_entry.place(anchor='n', relx=0.7, rely=0.6) # Password widgets password_label = tk.Label(signup_frame, text="PASSWORD", bg=DARK_CYAN, fg='white') password_label.place(anchor='n', relx=0.25, rely=0.75) self.password_entry = tk.Entry(signup_frame) self.password_entry.place(anchor='n', relx=0.7, rely=0.75) btn_frame = tk.Frame(signup_frame, bg=DARK_CYAN) btn_frame.place(relx=0.5, rely=0.85, relwidth=1, relheight=0.2, anchor='n') # login_btn = Button(btn_frame, text="Login", command=self.login, bg='white', fg="black", borderless=1) # login_btn.place(relx=0.3, rely=0.2, anchor='n') confirm_btn = Button(btn_frame, text="Confirm", bg='white', fg="black", borderless=1, command=self.sign_up_btn) confirm_btn.place(relx=0.5, rely=0.2, anchor='n')
class GuiNumsum: """Contains GUI setup for Numsum game.""" def __init__(self): """Initialize all the variables of the GUI and of Numsum.""" self.height = 700 self.width = 800 self.game = Numsum() self.text_color = '#57D9A3' self.button_color = '#3B3B3B' self.background_color = '#222222' self.font = 'Silom' self._root = Tk() self._root.title("Numsum") self._root.resizable(width=False, height=False) # Fixed size # The canvas is where the text and other game stats will be displayed self.canvas = Canvas(self._root, height=self.height, width=self.width, bg=self.background_color) self.canvas.pack() # A separate container inside the canvas to place the button grid self.frame = Frame(self._root) self.frame.place(relx=0.2, rely=0.192, relwidth=0.6, relheight=0.6) # 60% of the screen size # Expands rows and columns of the frame's grid for widget resizing, without this the buttons stay small. Grid.rowconfigure(self.frame, [0, 1, 2], weight=1) Grid.columnconfigure(self.frame, [0, 1, 2], weight=1) # Player 1 label self.player_one_label = Label(self.canvas, text='Player\n 1', font=[self.font, 40], bg=self.background_color, fg=self.text_color) self.player_one_label.place(relx=0.01, rely=0.02) # Player 2 label self.player_two_label = Label(self.canvas, text='Player\n 2', font=[self.font, 40], bg=self.background_color, fg=self.text_color) self.player_two_label.place(relx=0.80, rely=0.02) # A solid line that separates number pad from player labels self.canvas.create_line(0, 131, 800, 131, width=5, fill=self.text_color) # A collection (list) to hold the references to the buttons created below self.buttons = [] self._button_font_size = font.Font( size=30 ) # Buttons don't work consistently on MacOS, this setting helps out. # Initializes buttons in frame for index in range(1, 10): button_number = index # index-1 because the buttons numbers start at 1 and the list indices starting at 0. grid_index = index - 1 # lambda passes vars from this function as parameters to button_click and calls that function on each press. button = Button( self.frame, bg=self.button_color, fg=self.text_color, text=button_number, command=lambda index=grid_index, button_number=button_number: self.button_click(index, button_number)) # sets font on separate line because of MacOS button issues. button['font'] = self._button_font_size # Add the button to the window button.grid(row=floor((grid_index / 3)), column=(grid_index % 3), sticky="nsew") # Add a reference to the newly created button to the list 'buttons' self.buttons.append(button) # Rules button, triggers popout window self.rules_button = Button(self.canvas, text='Rules', font=[self.font, 15], bg=self.button_color, fg=self.text_color, width=60, height=40, command=self.popup_rules) self.rules_button.place(relx=0.91, rely=0.93) # Main tkinter loop self._root.mainloop() def button_click(self, index, button_number): """This function runs after each button is selected by a player. It takes the number selected and displays the chosen number. It then registers the move with the game, and checks to see if that move has ended the game.""" # Disable the button by index self.buttons[index].config(state="disabled", bg=self.background_color) self.display_chosen_number(button_number) self.game.make_move(button_number) self.check_game_end() def display_chosen_number(self, display_number): """Displays selected number on appropriate players side of the screen in a column.""" # Calculates space between displayed numbers by multiplying game length by 0.05, so every move increases the # space by that amount. This function runs BEFORE the move is made so 1 is added to game length preemptively. current_game_length = (self.game.game_length + 1) * 0.05 if self.game.get_current_turn( ) == 'first': # add to left side of screen screen_number = Label(self.canvas, text=display_number, font=[self.font, 40], bg=self.background_color, fg=self.text_color) screen_number.place(relx=0.085, rely=(0.25 + current_game_length)) else: # it is second players turn, add to right side of screen screen_number = Label(self.canvas, text=display_number, font=[self.font, 40], bg=self.background_color, fg=self.text_color) screen_number.place(relx=0.85, rely=(0.2 + current_game_length)) def check_game_end(self): """Checks if the game has ended, display's winner or draw, the calls the replay game function to see how the program should proceed.""" if self.game.get_current_state( ) != 'UNFINISHED': # Game has a winner or is a draw self._root.title(self.game.get_current_state() ) # Display's game state in title bar for x in range(len( self.buttons)): # Disables the remaining buttons self.buttons[x].config(state="disabled", bg=self.background_color) self.check_replay() # Play again buttons appears # Game has a winner, Display WINNER! with asterisk on left or right. if self.game.get_current_state() == 'FIRST PLAYER WON!!!': win_label = Label(self.canvas, text='*WINNER', font=[self.font, 80], bg=self.background_color, fg=self.text_color, justify='center') win_label.place(relx=0.23, rely=0.02) # Game has a winner, Display WINNER! with asterisk on left or right. elif self.game.get_current_state() == 'SECOND PLAYER WON!!!': win_label = Label(self.canvas, text='WINNER*', font=[self.font, 80], bg=self.background_color, fg=self.text_color, justify='center') win_label.place(relx=0.28, rely=0.02) # Game was a draw, display DRAW! in text elif self.game.get_current_state() == 'DRAW!': draw_label = Label(self.canvas, text='DRAW!', font=[self.font, 80], bg=self.background_color, fg=self.text_color, justify='center') draw_label.place(relx=0.32, rely=0.02) def restart_program(self): """Restarts the current program.""" python = sys.executable os.execl(python, python, *sys.argv) def check_replay(self): """Displays 'play again' label with 'yes' and 'no' buttons. Selecting 'yes' runs restart_program function, selecting 'no' exits the program.""" play_again_label = Label(self.canvas, text='Play Again?', font=[self.font, 20], bg=self.background_color, fg=self.text_color, justify='center') play_again_label.place(relx=0.418, rely=0.8) yes_button = Button(self.canvas, bg=self.button_color, fg=self.text_color, font=[self.font, 15], text='Yes', width=80, height=60, command=self.restart_program) no_button = Button(self.canvas, bg=self.button_color, fg=self.text_color, font=[self.font, 15], text='No', width=80, height=60, command=sys.exit) yes_button.place(relx=.395, rely=0.85) no_button.place(relx=0.5, rely=0.85) def popup_rules(self): """Creates 'Rules' button in bottom right of screen, click it opens a popup window with the rules and an 'Okay' button to close the window and return to the game.""" # Toplevel instead of Tk for secondary windows, you can only have one instance of Tk which is your main. popup = Toplevel(bg=self.background_color) popup.wm_title('Rules') popup_text = "Welcome to Numsum!\n" \ "The goal is to make a sum of 15 using exactly 3 numbers.\n" \ "When a number is chosen by one player, it becomes unavailable to choose for the other player.\n" \ "If all the numbers are selected and neither player can make a sum of 15, the game is a draw.\n" \ "Good Luck!" popup_label = Label(popup, text=popup_text, font=[self.font, 15], bg=self.background_color, fg=self.text_color, justify='center') popup_label.pack() # .destroy will close that window confirm_button = Button(popup, text='Okay', bg=self.button_color, fg=self.text_color, font=[self.font, 15], command=popup.destroy) confirm_button.pack() popup.mainloop()
def dateEntryPage(*args): hourString = StringVar() minString = StringVar() #Function to retrieve the custom date and time values from the user def getDateValues(): try: day = cal.selection_get() hour = hourString.get() minute = minString.get() SetDateToCustom(day.strftime("%A"), hour, minute) except ValueError: pass global flag flag = True today = datetime.date.today() mindate = datetime.date( today.year, today.month, today.day) #sets minimum date on the calendar as todays date maxdate = datetime.date(year=2030, month=12, day=30) #sets maximum date on the calendar #commands to retrive an image from the system which will be used to design the various widgets present in the GUI selDate_back_img = Image.open( "/Users/aneez.jah/Desktop/Y1S1 Coursework/Introduction to Computational Thinking/Mini Project/NSCanteenSystem/OtherDates/selectdate.png" ) Enter_Button_img = Image.open( "/Users/aneez.jah/Desktop/Y1S1 Coursework/Introduction to Computational Thinking/Mini Project/NSCanteenSystem/OtherDates/Enter_Button.png" ) set_button_img = Image.open( "/Users/aneez.jah/Desktop/Y1S1 Coursework/Introduction to Computational Thinking/Mini Project/NSCanteenSystem/OtherDates/Set_Button.png" ) selDate_Background = ImageTk.PhotoImage(selDate_back_img) Enter_Button = ImageTk.PhotoImage(Enter_Button_img) Set_Button = ImageTk.PhotoImage(set_button_img) s = ttk.Style() s.theme_use('clam') #initialization block for the widgets to be displayes to the user. Defines the various widgets and places them at an arbitrary location on the window customFrame = ttk.Frame(root, padding="0") background_label = Label(root, image=selDate_Background) background_label.image = selDate_Background # this is to keep a copy of the image in the file enterButton = Button(root, text="", command=curStoresPage, image=Enter_Button) setButton = Button(root, text="Set", command=getDateValues, image=Set_Button) backButton = Button(root, text="Go Back", command=mainScreen, image=back_button) cal = Calendar(root, font="Arial 14", selectmode='day', locale='en_US', mindate=mindate, maxdate=maxdate, disabledforeground='red', cursor="hand1", year=2018, month=2, day=5) hourEntry = ttk.Combobox(root, values=(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23), width=10, textvariable=hourString, state="readonly") hourEntry.current(9) #sets the default value of the combobox minuteEntry = ttk.Combobox( root, values=(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59), width=10, textvariable=minString, state="readonly") minuteEntry.current(29) #sets default value of combobox endProg = Button(root, text="", command=leavePage, image=CloseButton) #Placement block for the widgets to be displayed to the user. Defines the coordinates on the window at which each widget should be placed customFrame.place() background_label.place(x=0, y=0, relwidth=1, relheight=1) enterButton.place(x=650, y=340, height=146, width=128) setButton.place(x=520, y=340, height=146, width=128) backButton.place(x=30, y=400, height=50, width=50) cal.pack(expand=False) cal.place(x=250, y=150) hourEntry.place(x=250, y=380) minuteEntry.place(x=420, y=380) endProg.place(x=740, y=20, height=34, width=40)
def __init__(self, master, state): self.master = master self.master.title(state) self.state = state self.entering_frame = tk.Frame(self.master, bg=DARK_CYAN) self.entering_frame.place(relx=0.5, rely=0.25, relwidth=0.45, relheight=0.5, anchor='n') fontStyle = tkFont.Font(family="Lucida Grande", size=45) # Main header header = tk.Label(self.master, text="MALAYALAM AASHAN", bg=CHAMPAGNE, fg=DARK_PURPLE, font=fontStyle) header.place(anchor='n', relx=0.5, rely=0.1) # Welcome label welcome_label = tk.Label(self.entering_frame, text="Welcome!\nPlease Login or Sign Up", bg=DARK_CYAN, fg='white') welcome_label.place(anchor='n', relx=0.5, rely=0.1) # Username widgets username_label = tk.Label(self.entering_frame, text="USERNAME", bg=DARK_CYAN, fg='white') username_label.place(anchor='n', relx=0.25, rely=0.3) self.username_entry = tk.Entry(self.entering_frame) self.username_entry.place(anchor='n', relx=0.7, rely=0.3) # Password widgets password_label = tk.Label(self.entering_frame, text="PASSWORD", bg=DARK_CYAN, fg='white') password_label.place(anchor='n', relx=0.25, rely=0.5) self.password_entry = tk.Entry(self.entering_frame) self.password_entry.place(anchor='n', relx=0.7, rely=0.5) btn_frame = tk.Frame(self.entering_frame, bg=DARK_CYAN) btn_frame.place(relx=0.5, rely=0.8, relwidth=1, relheight=0.2, anchor='n') login_btn = Button(btn_frame, text="Login", command=self.login, bg='white', fg="black", borderless=1) login_btn.place(relx=0.3, rely=0.2, anchor='n') signup_btn = Button(btn_frame, text="Sign up", bg='white', fg="black", borderless=1, command=self.show_sign_up_frame) signup_btn.place(relx=0.7, rely=0.2, anchor='n')
dd_from.bind('<Button-1>', (lambda _: update_flag_from(dd_from.get_value()))) label_flag_from = Label(frame_mid_1, image='', bg=color_bg_1) label_flag_from.place(x=100, y=120, anchor='center') ## MID 2 img_swap = ImageTk.PhotoImage( Image.open(get_full_path('swap.png')).resize((30, 30), Image.ANTIALIAS)) btn_swap = Button(frame_mid_2, image=img_swap, width=50, height=40, command=on_swap_click, bg=color_bg_2) btn_swap.place(x=50, y=60, anchor='center') ## MID 3 label_3 = Label(frame_mid_3, text='To', font=('Helvetica', 18), bg=color_bg_1) label_3.place(x=100, y=20, anchor='center') code_to = StringVar() dd_to = Combobox_Autocomplete(frame_mid_3, justify='center', font=('Helvetica', 16), list_of_items=list_currency, textvariable=code_to) dd_to.place(x=100, y=60, width=150, height=40, anchor='center') dd_to.bind('<Return>', (lambda _: update_flag_to(dd_to.get_value()))) dd_to.bind('<Button-1>', (lambda _: update_flag_to(dd_to.get_value())))
class Review_Characters: def __init__(self, master, clicked_mod): self.master = master master.title("Review Characters") self.main_frame = tk.Frame(self.master, height=HEIGHT, width=WIDTH, bg='white', borderwidth=1) self.main_frame.pack() self.clicked = clicked_mod topborder = tk.Frame(self.main_frame, bg=LIGHT_GRAY) topborder.place(relx=0, rely=0, relwidth=1, relheight=0.07) header_font = tkFont.Font(family="Lucida Grande", size=24) header_label = tk.Label(topborder, text="Review Characters".upper(), font=header_font, fg='white', bg=LIGHT_GRAY) header_label.place(relx=0.05, rely=0.2) instructions = tk.Label( self.main_frame, text= "Click the button below to see the answer.\nWhen you think you have memorized it, hit confirm", fg=LIGHT_GRAY) instructions.place(relx=0.5, rely=0.2, anchor='center') self.current_char = tk.StringVar() self.answer = tk.StringVar() self.index = 0 self.training_set = [] if self.clicked == "Review Vowels": self.training_set = VOWELS elif self.clicked == "Review Consonants": self.training_set = CONSONANTS else: self.training_set = MODIFIERS self.learned_array = [] self.card_frame = tk.Frame(self.main_frame, bg=CHAMPAGNE, highlightbackground=MING, highlightthickness=6) self.card_frame.place(relx=0.5, rely=0.5, anchor='center', relheight=0.4, relwidth=0.45) self.current_char.set(self.training_set[self.index]) char_font = tkFont.Font(family="Lucida Grande", size=100) self.char_label = tk.Label(self.card_frame, textvariable=self.current_char, font=char_font, bg=CHAMPAGNE, fg='black') self.char_label.place(relx=0.5, rely=0.4, anchor='center') self.show_answer_btn = Button(self.card_frame, text="Show Answer", bg='white', fg='black', borderless=1, command=self.show_answer) self.show_answer_btn.place(relx=0.5, rely=0.8, anchor='center') # Buttons that will control the flow of cards seen self.prev_btn = Button(self.main_frame, text="Previous", bg=DARK_CYAN, fg='white', borderless=1, command=self.prev) self.prev_btn.place(relx=0.2, rely=0.5, anchor='center') self.next_btn = Button(self.main_frame, text="Next", bg=DARK_CYAN, fg='white', borderless=1, command=self.next) self.next_btn.place(relx=0.8, rely=0.5, anchor='center') bottomborder = tk.Frame(self.main_frame, bg=LIGHT_GRAY) bottomborder.place(relx=0, rely=0.93, relwidth=1, relheight=0.07) back = tk.Button(self.main_frame, text="Dashboard", command=self.go_back) back.place(relx=0.05, rely=0.1) # When card if flipped self.confirm_btn = Button(self.card_frame, text="Confirm", command=self.confirm) self.confirm_btn.place_forget() self.not_yet_btn = Button(self.card_frame, text="Not yet") self.not_yet_btn.place_forget() def show_answer(self): self.current_char.set(get_pronunciation(self.training_set[self.index])) self.show_answer_btn.place_forget() self.confirm_btn.place(relx=0.2, rely=0.8) self.not_yet_btn.place(relx=0.6, rely=0.8) def prev(self): if self.index == 0: self.index = (len(self.training_set) - 1) else: self.index = self.index - 1 self.current_char.set(self.training_set[self.index]) self.confirm_btn.place_forget() self.not_yet_btn.place_forget() self.show_answer_btn.place(relx=0.5, rely=0.8, anchor='center') def next(self): if self.index == (len(self.training_set) - 1): self.index = 0 else: self.index = self.index + 1 self.current_char.set(self.training_set[self.index]) self.confirm_btn.place_forget() self.not_yet_btn.place_forget() self.show_answer_btn.place(relx=0.5, rely=0.8, anchor='center') def go_back(self): review_write(G_USERNAME, self.clicked, self.learned_array) self.main_frame.destroy() Dashboard(self.master, "Dashboard Window") def confirm(self): if self.training_set[self.index] not in self.learned_array: self.learned_array.append(self.training_set[self.index])
def __init__(self): self.root = tkinter.Tk() self.root.title('Shopify | Scraper ') self.root.resizable(False, False) self.root.geometry('1000x700') frame = Frame(self.root) frame.pack() self.root.update() #left frame - MENU SIDE leftframe = Frame(self.root, bg='#F4F6F8') leftframe.pack(side=LEFT) leftframe.place(height=800, width=280, x=0, y=0) #right frame - DISPAY SIDE rightframe = Frame(self.root, bg=rightframe_background_color) rightframe.pack(side=RIGHT) rightframe.place(height=800, width=800, x=250, y=0) #Project Logo load = Image.open(os.getcwd() + "/imgs/logo.png") render = ImageTk.PhotoImage(load) img = Label(leftframe, image=render) img.image = render img.place(x=35, y=20) project_logo = Label(leftframe, text="data extractor", font=("Motiva Sans", 14, "bold", "italic"), bg='#F4F6F8', fg='black') project_logo.place(x=53, y=80) #reformat Button reformat_button = Button( leftframe, text="Reformat", width=20, command=lambda: reformat_dataset(self, "reformat-data")) reformat_button.place(x=25, y=200) validation_button = Button( leftframe, text="Validate", width=20, command=lambda: validate_dataset(self, "validate-data")) validation_button.place(x=25, y=250) count_button = Button( leftframe, text="Counting", width=20, command=lambda: pre_sort_dataset(self, "pre-sort-dataset")) count_button.place(x=25, y=300) download_button = Button(leftframe, text="Download", width=20, command=lambda: download_csv_from_dataset( self, "downlaod-csv-data")) download_button.place(x=25, y=350) quit_button = Button(leftframe, text="Quit", width=20, command=lambda: quit_page(self)) quit_button.place(x=25, y=400)
class Application(tk.Tk): def __init__(self): super().__init__() self.name = "" self.version = "V3.2.2" self.sampling_rate_ver = tk.IntVar() self.content = tk.StringVar() self.update_url = tk.StringVar() self.update_info = tk.StringVar() self.read_url = "" self.read_str = tk.StringVar() self.lock = threading.Lock() # 创建一个顶级弹窗 self.withdraw() self.top = tk.Toplevel() self.top.title("请勿关闭") if sys.platform[:3] == "win": self.top.iconbitmap("logo.ico") self.top.attributes("-alpha", 0.99) def close_fun(): ans = messagebox.askokcancel(title="警告", message="首次使用需要网络,确定要关闭吗?") if ans: self.top.destroy() self.destroy() self.top.protocol("WM_DELETE_WINDOW", close_fun) # 设置窗口大小 width = 301 height = 169 # 获取屏幕尺寸以计算布局参数,使窗口居于屏幕中央 screenwidth = self.top.winfo_screenwidth() screenheight = self.top.winfo_screenheight() geometry_str = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 3) self.top.geometry(geometry_str) self.top.resizable(width=False, height=False) tk.Label( self.top, text="首次使用会自动下载一些工具文件,可\r\n能需要等待一分钟左右,过程中请保持\r\n网络正常连接,请稍等。。。。。。", wraplength=280, justify="left", font=("宋体", 12), fg="red").pack(pady=10) self.downBar = ttk.Progressbar(self.top, length=110, mode="determinate") self.downBar.pack(fill=tk.X, padx=25, pady=15) self.top.withdraw() # 创建 t2 = threading.Thread(target=self.init_fun) # 守护 !!! t2.setDaemon(True) # 启动 t2.start() self.createWidgets() def init_fun(self): # 创建输出文件夹 mkdir("WAV/") # print("开始下载ffmpeg包") if sys.platform[:3] == "win": ffmpeg_file_name = "ffmpeg.exe" is_64bits = sys.maxsize > 2**32 if is_64bits: ffmpeg_file_url = "https://ncstatic.clewm.net/rsrc/2020/1030/13/7b83b0086583af8a79637e995807b964.obj" else: ffmpeg_file_url = "https://ncstatic.clewm.net/rsrc/2020/0920/08/67baff128cddba3d1104b7be2f9f84fa.obj" if sys.platform == "darwin": ffmpeg_file_name = "ffmpeg" ffmpeg_file_url = "https://ghproxy.com/https://evermeet.cx/ffmpeg/get" if not os.path.exists(ffmpeg_file_name): self.top.deiconify() try: str_out = [ './aria2c', '--check-certificate=false', '-x', '8', '-o', "ffmpeg.7z", ffmpeg_file_url ] print(str_out) if sys.platform[:3] == "win": si = subprocess.STARTUPINFO() si.dwFlags = subprocess.CREATE_NEW_CONSOLE | subprocess.STARTF_USESHOWWINDOW si.wShowWindow = subprocess.SW_HIDE process = subprocess.Popen(str_out, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding="utf-8", text=True, startupinfo=si) if sys.platform == "darwin": process = subprocess.Popen(str_out, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding="utf-8", text=True) for line in process.stdout: # print(line) status_res = re.search(r'\((?P<status>[\s\S]*?)\):', line) if status_res is not None: if status_res.groupdict()['status'] == "ERR": raise Exception("下载错误") percent_res = re.search(r'\((?P<percent>[\s\S]*?)%\)', line) if percent_res is not None: progress = percent_res.groupdict()['percent'] print(progress) self.downBar["value"] = progress self.top.update() process.wait() if process.poll() == 0: # 解压文件 str_out = ['./7z', 'x', "ffmpeg.7z"] print(str_out) if sys.platform[:3] == "win": si = subprocess.STARTUPINFO() si.dwFlags = subprocess.CREATE_NEW_CONSOLE | subprocess.STARTF_USESHOWWINDOW si.wShowWindow = subprocess.SW_HIDE process_1 = subprocess.Popen(str_out, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding="utf-8", text=True, startupinfo=si) if sys.platform == "darwin": process_1 = subprocess.Popen(str_out, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding="utf-8", text=True) process_1.wait() if process_1.poll() == 0: for item_7z in glob.glob("ffmpeg*.7z"): os.remove(item_7z) if sys.platform == "darwin": os.chmod("./ffmpeg", 0o755) print("解压完成") self.downBar["value"] = 110 self.top.destroy() self.deiconify() except Exception as e: print("网络未连接,请检查连接后重试") print(e) self.top.withdraw() messagebox.showwarning(title="警告", message="网络未连接,请检查连接后重试(首次使用需要网络)") self.top.destroy() self.destroy() else: self.top.destroy() self.deiconify() def createWidgets(self): self.title("嗖音HOME " + self.version[1:] + " - 独居者") if sys.platform[:3] == "win": self.iconbitmap("logo.ico") self.attributes("-alpha", 0.99) # 设置颜色 progress_color = "#1E94A0" progress_chunk_color = "#FA7268" declare_color = "red" update_color = "#F9425B" update_bg_color = "#0071CF" font_color = "#EBE5D9" btn_color = "#14B09B" frame_color = "#0359AE" # 设置字体 if sys.platform[:3] == "win": l_font = ("宋体", 12) m_font = ("宋体", 11) s_font = ("宋体", 9) if sys.platform == "darwin": l_font = ("宋体", 16) m_font = ("宋体", 15) s_font = ("宋体", 12) # 设置窗口大小 width = 603 height = 339 # 获取屏幕尺寸以计算布局参数,使窗口居于屏幕中央 screenwidth = self.winfo_screenwidth() screenheight = self.winfo_screenheight() geometry_str = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 3) self.geometry(geometry_str) self.resizable(width=False, height=False) L_frame = tk.Frame(width=373, height=height, bg=frame_color) R_frame = tk.Frame(width=230, height=height, bg=frame_color) L_frame.grid(row=0, column=0) R_frame.grid(row=0, column=1) self.update_info.set("检测更新中......") # 创建 t = threading.Thread(target=self.update_fun) read_t = threading.Thread(target=self.read_fun) # 守护 !!! t.setDaemon(True) read_t.setDaemon(True) # 启动 t.start() read_t.start() # 右边开始布局 updateLab = tk.Label(R_frame, textvariable=self.update_info, font=l_font, bg=update_bg_color, fg=update_color) updateLab.place(x=0, y=0, width=230, height=25) updateLab.bind("<Button-1>", self.open_browser) if sys.platform[:3] == "win": self.text = tk.Text(R_frame, width=5, height=5, bd=1, relief="solid", font=s_font, bg=frame_color, fg=font_color) if sys.platform == "darwin": self.text = tk.Text(R_frame, width=5, height=5, bd=1, relief="solid", font=s_font, bg=frame_color, fg=font_color, highlightthickness=0) self.text.place(x=30, y=50, width=170, height=155) self.text.insert(tk.INSERT, "有什么想对开发者说的可以说") self.text.bind("<Button-1>", self.del_show) if sys.platform[:3] == "win": buttonSend = tk.Button(R_frame, text="给开发者的话", command=self.send_message, font=m_font, bd=0, bg=btn_color, fg=font_color, activeforeground=font_color, activebackground=frame_color) if sys.platform == "darwin": buttonSend = Button(R_frame, text="给开发者的话", command=self.send_message, font=m_font, borderless=1, bg=btn_color, fg=font_color, activeforeground=font_color, activebackground=frame_color) buttonSend.place(x=65, y=230, width=101, height=30) declare_str = "声明:仅供个人录制音频转换使用" labDeclare = tk.Label(R_frame, text=declare_str, wraplength=151, justify="left", font=s_font, bd=1, relief="solid", bg=frame_color, fg=declare_color) labDeclare.place(x=40, y=282, width=151, height=41) # 左边开始布局 self.read_str.set("随机阅读:正在加载中......") labShow = tk.Label(L_frame, textvariable=self.read_str, wraplength=252, justify="left", anchor="w", padx=5, bd=1, relief="solid", bg=frame_color, fg=font_color) labShow.place(x=30, y=25, width=313, height=70) labReadAll = tk.Label(L_frame, text="查看全文", bg=frame_color, fg="#22B14C") labReadAll.place(x=287, y=26, width=55, height=68) labReadAll.bind("<Button-1>", self.read_page) self.content.set("请选择要转换的音频文件") lab = tk.Label(L_frame, textvariable=self.content, font=m_font, bg=frame_color, fg=font_color) lab.place(x=30, y=110, width=313, height=20) if sys.platform[:3] == "win": self.entry_url = tk.Entry(L_frame, validate="focusin", validatecommand=self.del_url_show, font=s_font, bd=1, relief="solid", bg=frame_color, fg=font_color) if sys.platform == "darwin": self.entry_url = tk.Entry(L_frame, validate="focusin", validatecommand=self.del_url_show, font=s_font, bd=1, relief="solid", bg=frame_color, fg=font_color, highlightthickness=0) self.entry_url.place(x=30, y=160, width=238, height=30) self.entry_url.insert(0, "请输入分享链接即可") if sys.platform[:3] == "win": self.buttonOpenUrl = tk.Button(L_frame, text="网络转换", command=self.urlfile_convert, font=m_font, bd=0, bg=btn_color, fg=font_color, activeforeground=font_color, activebackground=frame_color) if sys.platform == "darwin": self.buttonOpenUrl = Button(L_frame, text="网络转换", command=self.urlfile_convert, font=m_font, borderless=1, bg=btn_color, fg=font_color, activeforeground=font_color, activebackground=frame_color) self.buttonOpenUrl.place(x=268, y=160, width=75, height=30) if sys.platform[:3] == "win": self.buttonStart = tk.Button(L_frame, text="本地转换", command=self.localfile_convert, font=m_font, bd=0, bg=btn_color, fg=font_color, activeforeground=font_color, activebackground=frame_color) if sys.platform == "darwin": self.buttonStart = Button(L_frame, text="本地转换", command=self.localfile_convert, font=m_font, borderless=1, bg=btn_color, fg=font_color, activeforeground=font_color, activebackground=frame_color) self.buttonStart.place(x=268, y=200, width=75, height=30) if sys.platform[:3] == "win": buttonOpen = tk.Button(L_frame, text="打开本地文件", command=self.openfile, font=m_font, bd=0, bg=btn_color, fg=font_color, activeforeground=font_color, activebackground=frame_color) if sys.platform == "darwin": buttonOpen = Button(L_frame, text="打开本地文件", command=self.openfile, font=m_font, borderless=1, bg=btn_color, fg=font_color, activeforeground=font_color, activebackground=frame_color) buttonOpen.place(x=110, y=200, width=101, height=30) labOut = tk.Label(L_frame, text="输出配置:", justify="left", font=m_font, bg=frame_color, fg=font_color) labOut.place(x=30, y=250, width=75, height=30) buttonVer = tk.Checkbutton(L_frame, text="旧版", font=m_font, variable=self.sampling_rate_ver, bg=frame_color, fg=font_color, activeforeground=font_color, activebackground=frame_color, selectcolor=frame_color) buttonVer.place(x=110, y=250, width=71, height=30) if sys.platform[:3] == "win": buttonFile = tk.Button(L_frame, text="浏览输出", command=show_file_path, font=s_font, bd=0, bg=btn_color, fg=font_color, activeforeground=font_color, activebackground=frame_color) if sys.platform == "darwin": buttonFile = Button(L_frame, text="浏览输出", command=show_file_path, font=s_font, borderless=1, bg=btn_color, fg=font_color, activeforeground=font_color, activebackground=frame_color) buttonFile.place(x=268, y=291, width=75, height=23) labHelp = tk.Label(L_frame, text="<使用指南>", font=s_font, bg=frame_color, fg=font_color) labHelp.place(x=10, y=306, width=75, height=23) labHelp.bind("<Button-1>", self.show_help) progressbar_style = ttk.Style() progressbar_style.theme_use('alt') progressbar_style.configure("blue.Vertical.TProgressbar", troughcolor=progress_color, background=progress_chunk_color, troughrelief="flat") self.progressBar = ttk.Progressbar(self, style="blue.Vertical.TProgressbar", length=115, mode="determinate", orient="vertical") self.progressBar.place(x=368, y=0, width=5, height=height) # 反馈信息发送函数,具体实现可以自定义,钉钉机器人和与你机器人均可 # 钉钉机器人文档:https://ding-doc.dingtalk.com/doc#/serverapi2/krgddi # 与你机器人文档:http://www.uneed.com/openapi/pages/index.html#/chatbot/intro def send_message(self): try: # print(self.text.get("1.0", "end").strip('\n')) msg = self.text.get("1.0", "end").strip('\n') if msg == "" or msg == "有什么想对开发者说的可以说": messagebox.showwarning(title="警告", message="请输入内容后发送") return ret_message = send_ding_msg(msg) if ret_message[0] == "showinfo": messagebox.showinfo(title=ret_message[1], message=ret_message[2]) if ret_message[0] == "showwarning": messagebox.showwarning(title=ret_message[1], message=ret_message[2]) if ret_message[0] == "showerror": messagebox.showerror(title=ret_message[1], message=ret_message[2]) except Exception as e: print("网络未连接,请检查连接后重试") print(e) messagebox.showwarning(title="警告", message="网络未连接,请检查连接后重试") def del_show(self, event): print(event) self.text.delete("1.0", "end") def del_url_show(self): self.entry_url.delete(0, "end") def urlfile_thread(self, music_url): self.lock.acquire() try: self.content.set("请选择要转换的音频文件") try: music_data = Amusic.get_all_music_parm(music_url) if music_data[0] == "null" and music_data[1] == "null": print("不支持此分享链接或者链接格式错误") messagebox.showwarning(title="警告", message="不支持此分享链接或者链接格式错误") # 恢复本地转换按钮 self.buttonStart.config(state="normal") return if music_data[1] == "null": music_name = music_data[0] self.content.set(music_name) messagebox.showwarning(title="警告", message=music_name) # 恢复本地转换按钮 self.buttonStart.config(state="normal") return music_name = music_data[0] music_play_url = music_data[1] except Exception as e: print("网络未连接,请检查连接后重试") print(e) messagebox.showwarning(title="警告", message="网络未连接,请检查连接后重试") # 恢复本地转换按钮 self.buttonStart.config(state="normal") return self.content.set(music_name) start_time = time.perf_counter() sampling_rate = "48000" if self.sampling_rate_ver.get() == 1: sampling_rate = "32000" self.ffmpeg_run(music_play_url, music_name, sampling_rate) elapsed = (time.perf_counter() - start_time) print("耗时:%6.2f" % elapsed + "秒") self.content.set("耗时:%6.2f" % elapsed + "秒") finally: self.lock.release() # 恢复本地转换按钮 self.buttonStart.config(state="normal") def urlfile_convert(self): # 禁用本地转换按钮 self.buttonStart.config(state="disabled") music_url = self.entry_url.get() if music_url == "" or music_url == "请输入分享链接即可": messagebox.showwarning(title="警告", message="请输入分享链接后执行") # 恢复本地转换按钮 self.buttonStart.config(state="normal") return if not self.lock.locked(): temp_thread = threading.Thread(target=self.urlfile_thread, args=(music_url, )) temp_thread.setDaemon(True) temp_thread.start() def openfile(self): # print("文本框内容:" + entry_url.get()) file_path = filedialog.askopenfilename(title="选择音频文件") filename = os.path.basename(file_path) self.name = file_path print(self.name) self.content.set(filename) def ffmpeg_run(self, input_file, music_name, sampling_rate): self.progressBar["value"] = 0 self.update() temp_path = "TEMP/" mkdir(temp_path) temp_music_name = str(round(time.time() * 1000)) str_out = [ './ffmpeg', '-i', input_file, '-ar', sampling_rate, '-ac', '1', '-acodec', 'pcm_s16le', '-hide_banner', temp_path + temp_music_name + ".wav" ] print(str_out) if sys.platform[:3] == "win": si = subprocess.STARTUPINFO() si.dwFlags = subprocess.CREATE_NEW_CONSOLE | subprocess.STARTF_USESHOWWINDOW si.wShowWindow = subprocess.SW_HIDE process = subprocess.Popen(str_out, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding="utf-8", text=True, startupinfo=si) if sys.platform == "darwin": process = subprocess.Popen(str_out, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding="utf-8", text=True) for line in process.stdout: # print(line) duration_res = re.search(r'\sDuration: (?P<duration>\S+)', line) if duration_res is not None: duration = duration_res.groupdict()['duration'] duration = re.sub(r',', '', duration) result = re.search(r'\stime=(?P<time>\S+)', line) if result is not None: elapsed_time = result.groupdict()['time'] progress = (get_seconds(elapsed_time) / get_seconds(duration)) * 100 print(elapsed_time) print(progress) # self.content.set("进度:%3.2f" % progress + "%") self.progressBar["value"] = progress self.update() process.wait() if process.poll() == 0: infile_path = temp_path + temp_music_name + ".wav" outfile_path = "WAV/" + music_name + ".wav" del_wavparm(infile_path) shutil.move(infile_path, outfile_path) del_file(temp_path) print("success:", process) # 设置终点 self.progressBar["value"] = 115 else: print("error:", process) def localfile_thread(self): self.lock.acquire() try: start_time = time.perf_counter() sampling_rate = "48000" if self.sampling_rate_ver.get() == 1: sampling_rate = "32000" music_name = os.path.splitext(os.path.basename(self.name))[0] self.ffmpeg_run(self.name, music_name, sampling_rate) elapsed = (time.perf_counter() - start_time) print("耗时:%6.2f" % elapsed + "秒") self.content.set("耗时:%6.2f" % elapsed + "秒") finally: self.lock.release() # 恢复网络转换按钮 self.buttonOpenUrl.config(state="normal") def localfile_convert(self): # 禁用网络转换按钮 self.buttonOpenUrl.config(state="disabled") if not self.name: messagebox.showwarning(title="警告", message="请先选择文件后执行") # 恢复网络转换按钮 self.buttonOpenUrl.config(state="normal") return if not self.lock.locked(): temp_thread = threading.Thread(target=self.localfile_thread) temp_thread.setDaemon(True) temp_thread.start() def open_browser(self, event): print(event) open_url = self.update_url.get() if open_url != "": webbrowser.open(open_url) def read_fun(self): pre_url = "https://blog.csdn.net/qq_41730930" try: read_data_url = "https://cdn.jsdelivr.net/gh/space9bug/sharesoftware@master/s/articles.json" headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36' } response = requests.request("GET", read_data_url, headers=headers) response.encoding = "utf-8" response_code = response.status_code if response_code == 200: read_data = json.loads(response.text) if read_data is not None: read_index = random.randint(0, len(read_data) - 1) article_title = read_data[read_index][0] if article_title is not None: self.read_str.set("随机阅读:" + article_title) article_url = read_data[read_index][1] if article_url is not None: if re.match(r"^\d*$", article_url) is None: self.read_url = article_url else: self.read_url = pre_url + "/article/details/" + article_url else: self.read_url = pre_url else: self.read_url = pre_url else: self.read_url = pre_url except Exception as e: print("网络未连接,请检查连接后重试") print(e) self.read_url = pre_url def read_page(self, event): print(event) if self.read_url != "": webbrowser.open(self.read_url) def show_help(self, event): print(event) self.update() # 获取主窗口的左上角坐标 origin_x = self.winfo_x() origin_y = self.winfo_y() # 获取主窗口的宽、高 origin_width = self.winfo_width() origin_height = self.winfo_height() # 设置窗口大小 width = 300 height = 169 # 创建一个顶级弹窗 helpTop = tk.Toplevel() helpTop.title("使用指南") if sys.platform[:3] == "win": helpTop.iconbitmap("logo.ico") helpTop.attributes("-alpha", 0.99) geometry_str = '%dx%d+%d+%d' % (width, height, origin_x + (origin_width - width) / 2, origin_y + (origin_height - height) / 2) helpTop.geometry(geometry_str) helpTop.resizable(width=False, height=False) helpTop.focus_set() help_str = "使用指南\n1.本地音频转换:打开选择本地文件,开始进行转换\n2.网络分享音频:支持唱鸭、全民K歌、唱吧、荔枝、喜马拉雅、斗歌、酷狗唱唱、猫爪弹唱、弹唱达人、爱唱、闪歌、VV音乐、爱听、酷狗音乐大字版、酷我K歌、全民K诗、天籁K歌、咪咕K歌、酷狗K歌" helpMessage = tk.Message(helpTop, text=help_str, justify="left", width=260) helpMessage.place(x=0, y=0, width=300, height=169) def update_fun(self): try: url = "https://cdn.jsdelivr.net/gh/space9bug/sharesoftware@master/s/version.json" # 因为jsDelivr缓存更新时间为24小时,所以推迟版本更新检测。 release_time = "2021-02-27 15:30" hours = (time.mktime(time.strptime(release_time, "%Y-%m-%d %H:%M")) - round(time.time())) // 3600 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36' } response = requests.request("GET", url, headers=headers) print(response.text) version_data = json.loads(response.text) latest_version = version_data["latestVersion"] if hours >= 24 and self.version != latest_version: print(version_data["downUrl"]) self.update_info.set(version_data["info"]) self.update_url.set(version_data["downUrl"]) messagebox.showinfo(title="更新提醒:" + self.version, message="新的更新来啦,为了您有更好的体验,建议您点击界面右上角进行更新。") else: self.update_info.set("已是最新版本:" + self.version) self.update_url.set(version_data["downUrl"]) # burying_point() except Exception as e: print("网络未连接,请检查连接后重试") print(e) self.update_info.set("已是最新版本:" + self.version)