from utils import swap, generate_boxes, Box from tkinter import Tk, Canvas import random import time tk = Tk() tk.title('Bubble Sort') # Canvas HEIGHT, WIDTH = 500, 1000 canvas = Canvas(tk, height=HEIGHT, width=WIDTH) canvas.pack() def set_color(box: Box, color: str, canvas: Canvas) -> None: '''Cahnge the color of the box''' canvas.itemconfig(box.box, fill=color) tk.update() def bubble_sort(boxes): initial_color = "#2299AB" comparision_color = "#8D00FF" final_color = "#00FFCE" animation_speed = 1 # Set all boxes color to initial color for box in boxes: set_color(box, initial_color, canvas) n = len(boxes)
canvas.draw() canvas.get_tk_widget().pack() toolbar = NavigationToolbar2Tk(canvas, window3) toolbar.update() canvas.get_tk_widget().pack() def ask_window(): fp = filedialog.askopenfilename() e7.insert(END, fp) window = Tk() window.title("Ode v1.0") window.geometry("750x240+120+120") window.resizable(False, False) l0 = Label(window, text="y''+p(x)*y'+q(x)*y=f(x) [a,b]") l0.config(font=("Arial", 15)) l0.place(x=50, y=20) entryText1 = tk.StringVar() e1 = Entry(window, textvariable=entryText1, font=("Arial", 12), width=10) e1.place(x=50, y=60) entryText1.set("a=") entryText2 = tk.StringVar() e2 = Entry(window, textvariable=entryText2, font=("Arial", 12), width=10)
b8.state(['!disabled']) b9.config(text= " ") b9.state(['!disabled']) def Restart(): global p1,p2,mov,ActivePlayer p1.clear(); p2.clear() mov,ActivePlayer = 0,1 root.title("Tic Tac Toe : Player 1") EnableAll() root = Tk() root.title("Tic Tac toe : Player 1") st = ttk.Style() st.configure("my.TButton", font=('Chiller',24,'bold')) b1 = ttk.Button(root, text=" ", style="my.TButton") b1.grid(row=1, column=0, sticky="nwse", ipadx=50,ipady=50) b1.config(command = lambda : ButtonClick(1)) b2 = ttk.Button(root, text=" ",style ="my.TButton") b2.grid(row=1, column=1, sticky="snew", ipadx=50, ipady=50) b2.config(command = lambda : ButtonClick(2)) b3= ttk.Button(root, text=" ",style="my.TButton") b3.grid(row=1, column=2, sticky="snew", ipadx=50,
# ========================输入区开始======================== refer_file_path = "/Users/alicewish/Documents/GitHub/Mac-App-Translation/总词典.txt" # 词典文件的地址 # ================按行读取参考文本并字典化================ refer_dict = {} # 创建一个字典 with open(refer_file_path) as fin: for line in fin: refer_line = (line.replace('\n', '')).replace('\t', '') if "|" in refer_line: # 接受key|value格式 split_line = refer_line.split("|") refer_dict[split_line[0]] = split_line[1] # ================读取剪贴板================ from tkinter import Tk r = Tk() read_text = r.clipboard_get() text_readline = read_text.splitlines() print(text_readline) # ================按行读取输入文本================ output_readline = [] # 初始化按行存储数据列表,不接受换行符 untranslated_check_set = set() # 初始化为空集合 translated_check_set = set() # 初始化为空集合 translated_readline = [] # 初始化按行存储数据列表,不接受换行符 count = 0 for i in range(len(text_readline)): line = text_readline[i] input_line = (line.replace('\n', '')).replace('\t', '') # 无视换行和制表符
def start(): root = Tk() main(root) root.mainloop()
def TransitionOnClick(self): root = Tk() grid1 = Grid(root, True) root.mainloop()
from tkinter import Label, Tk import time app_window = Tk() app_window.title("Digital Clock") app_window.geometry("420x150") app_window.resizable(1,1) text_font= ("Boulder", 68, 'bold') background = "#f2e750" foreground= "#363529" border_width = 25 label = Label(app_window, font=text_font, bg=background, fg=foreground, bd=border_width) label.grid(row=0, column=1) def digital_clock(): time_live = time.strftime("%H:%M:%S") label.config(text=time_live) label.after(200, digital_clock) digital_clock() app_window.mainloop()
stopbits=1, timeout=None, rtscts=1) # DEFAULT SIGNAL PARAMETERS: # (F_max should be changed for the new RF-chain with the voltage amplifier) num_values = 200 # must be even F_min_df = 1216.7 # Minimum frequency of the radar signal [MHz] # 0.0 V <-> 1216.7 MHz F_max_df = 2902.5 # Maximum frequency of the radar signal [MHz] # 3.3 V <-> 1439.3 MHz, 25.0 V <-> 2902.5 MHz T_df = 20 # Period of the signal in [ms] W_form_df = 1 # 1 - triangular, 2 - rectangular, 3 - sawtooth waveforms, (4 - no transmission) #------------------------------------------------------------------------------------------ # Create a MAIN WINDOW named "master": master = Tk() # Set geometry and title of the main window: master.geometry( '1100x400+200+100') # Size of the window(x,y) + position on screen (x,y) master.minsize(width=1000, height=300) master.title('GPR Control Panel') try: master.iconbitmap("gpr_icon.ico") # Icon of the window except TclError: print('No ico file found') # Load the logo image: logo = ImageTk.PhotoImage(file="GPR_logo.gif")
def main(): print('Initializing main function') print('Folder selection') folder_images = '/home/mauricio/PosesProcessed/folder_images' folder_images_draw = '/home/mauricio/PosesProcessed/folder_images_draw' Tk().withdraw() # Getting options init_dir = '/home/mauricio/Videos/Oviedo' options = {'initialdir': init_dir} dir_name = askdirectory(**options) if not dir_name: raise Exception('Directory not selected') # Create directory if does not exists if not os.path.isdir(folder_images): os.makedirs(folder_images) # Create directory if does not exists if not os.path.isdir(folder_images_draw): os.makedirs(folder_images_draw) # Initializing openpose instance instance_pose = ClassOpenPose() for root, subdirs, files in os.walk(dir_name): for file in files: full_path = os.path.join(root, file) print('Processing {0}'.format(full_path)) extension = ClassUtils.get_filename_extension(full_path) if extension == '.mjpeg': file_info = ClassMjpegReader.process_video(full_path) else: print('Extension ignored: {0}'.format(extension)) continue # Getting idcam from file id_cam = full_path.split('/')[-2] print('IdCam: {0}'.format(id_cam)) for index, info in enumerate(file_info): print('Processing {0} of {1} from {2}'.format(index, len(file_info), full_path)) frame = info[0] ticks = info[1] image_np = np.frombuffer(frame, dtype=np.uint8) image = cv2.imdecode(image_np, cv2.IMREAD_ANYCOLOR) arr, image_draw = instance_pose.recognize_image_tuple(image) min_score = 0.05 arr_pass = list() for elem in arr: if ClassUtils.check_vector_integrity_pos(elem, min_score): arr_pass.append(elem) if len(arr_pass) > 0: # Draw rectangles for all candidates for person_arr in arr_pass: pt1, pt2 = ClassUtils.get_rectangle_bounds(person_arr, min_score) cv2.rectangle(image_draw, pt1, pt2, (0, 0, 255), 5) # Overwriting 1 full_path_images = os.path.join(folder_images, '{0}_{1}.jpg'.format(ticks, id_cam)) print('Writing image {0}'.format(full_path_images)) cv2.imwrite(full_path_images, image) # Overwriting 2 full_path_draw = os.path.join(folder_images_draw, '{0}_{1}.jpg'.format(ticks, id_cam)) print('Writing image {0}'.format(full_path_images)) cv2.imwrite(full_path_draw, image_draw) print('Done!')
def setUpClass(cls): cls.root = Tk() cls.root.withdraw()
''' This demo shows you how you can create a new image by clicking the screen. ''' from tkinter import Canvas, Tk import utilities import keycodes gui = Tk() gui.title('Keyboard Event Handler') # initialize canvas: window_width = gui.winfo_screenwidth() window_height = gui.winfo_screenheight() canvas = Canvas(gui, width=window_width, height=window_height, background='white') canvas.pack() ########################## YOUR CODE BELOW THIS LINE ############################## KEY_PRESS = '<Key>' utilities.make_circle(canvas, (window_width/2, window_height/2), 50, color='hotpink', tag='circle') def move_circle(event): distance = 10 if event.keycode == keycodes.get_up_keycode(): utilities.update_position_by_tag(canvas, tag='circle', x=0, y=-distance) elif event.keycode == keycodes.get_down_keycode(): utilities.update_position_by_tag(canvas, tag='circle', x=0, y=distance) elif event.keycode == keycodes.get_left_keycode(): utilities.update_position_by_tag(canvas, tag='circle', x=-distance, y=0)
def give_feedback(self): """ Opens a text entry window where the user enters feedback, saves the feedback as a string with the date of writing it and saves in the json database (under 'Feedback' key) Arguments: patient's instance (username to identify the patient key in the database) Returns: updates json database ('Feedback') for the patient with feedback (string date+entry text) messagebox """ if self.assigned_gp == '': messagebox.showinfo( "No GP", 'You do not have any assigned GP who could accept your feedback.' ) return None # sets up the window and fonts that will be used fb_window = Tk() fb_window.title('UCLH patient portal: Feedback') fb_window.geometry("800x600") # takes the entry from the text widget, connects it with the date and updates the database def submit(): try: user_entry = feedback_box.get("1.0", 'end-1c') if len(user_entry) > 0: database = json.load(open('../uch_system/database.json')) feedback_date = str(datetime.date.today( )) # assumes 'today' as the day of writing full_feedback = feedback_date + ': ' + user_entry # creates string of date and entry database[self.username]['Feedback'].append( full_feedback) # appends the list of user's feedbacks json.dump(database, open('../uch_system/database.json', 'w')) fb_window.destroy() messagebox.showinfo("Feedback", "Your feedback has been submitted" ) # raises messagebox else: messagebox.showinfo("Alert", "You cannot upload empty feedback.") except ValueError: messagebox.showinfo( "Error", "We are sorry, the function is not working at the moment") Label(fb_window, text="Write your feedback in the box below.").place( relx=0.5, rely=0.15, anchor=CENTER) feedback_box = Text(fb_window, bg='honeydew2', width=60, height=20) # text entry window feedback_box.place(relx=0.5, rely=0.5, anchor=CENTER) Label(fb_window, text="Thank you for providing the feedback, it will be carefully evaluated by your GP.") \ .place(relx=0.5, rely=0.8, anchor=CENTER) # button that calls the submit function submit_button = Button(fb_window, text="Submit", command=submit) submit_button.place(relx=0.5, rely=0.88, anchor=CENTER) fb_window.mainloop()
def my_summary(self): """ The window that provides patient with summary of their health status. Arguments: instance of patient class (with the parameters from database) Returns: set of labels with the information from database """ from datetime import datetime # sets up the window and fonts that will be used summary_window = Tk() summary_window.title('Patient health summary') summary_window.geometry('1000x750+80+40') fontStyle2 = tkFont.Font(family="Lucida Grande", size=16) # demographic information about the patient Label(summary_window, text=self.f_name + ' ' + self.l_name, font=fontStyle2).place(relx=0.5, rely=0.08, anchor=CENTER) if self.dob == 'TBC': # if patient did not enter the DOB in correct format/ unknown exception Label(summary_window, text='Date of Birth: not uploaded').place(relx=0.5, rely=0.13, anchor=CENTER) Label(summary_window, text='Age: not uploaded').place(relx=0.5, rely=0.16, anchor=CENTER) else: datetime_object = datetime.strptime( self.dob, '%d/%m/%Y') # rewrites the string into datetime object datetime_object2 = datetime.strftime( datetime_object, '%d.%m.%Y') # changes format of datetime object Label(summary_window, text='Date of Birth: ' + datetime_object2).place(relx=0.5, rely=0.13, anchor=CENTER) age = datetime.today( ).year - datetime_object.year # calculates the age Label(summary_window, text='Age: ' + str(age)).place(relx=0.5, rely=0.16, anchor=CENTER) Label(summary_window, text='NHS number: ' + str(self.nhs_number)).place(relx=0.5, rely=0.19, anchor=CENTER) Label(summary_window, text='Telephone number: ' + str(self.tel_number)).place(relx=0.5, rely=0.22, anchor=CENTER) Label(summary_window, text='Gender: ' + self.gender).place(relx=0.5, rely=0.25, anchor=CENTER) # prints regular non-prescribed drugs if not self.regular_drugs: Label(summary_window, text='You have not claimed any regular non-prescribed drugs' ).place(relx=0.5, rely=0.28, anchor=CENTER) else: drug_string = '' for drug in self.regular_drugs: drug_string += ('#' + drug + ' ' ) # creates string of non-prescription drugs Label(summary_window, text='Non-prescription drugs: ' + drug_string).place( relx=0.5, rely=0.28, anchor=CENTER) # prints patient's allergies if not self.allergies: Label(summary_window, text='You have not claimed any allergies').place( relx=0.5, rely=0.31, anchor=CENTER) else: allergy_string = '' for allergy in self.allergies: allergy_string += ('#' + allergy + ' ' ) # creates string of allergies Label(summary_window, text='Allergies: ' + allergy_string).place(relx=0.5, rely=0.31, anchor=CENTER) # BMI calculator with two entries and submit button input_weight = Entry(summary_window) input_weight.place(relx=0.30, rely=0.36, anchor=CENTER) Label(summary_window, text='My Weight [kg]').place(relx=0.15, rely=0.36, anchor=CENTER) input_height = Entry(summary_window) input_height.place(relx=0.60, rely=0.36, anchor=CENTER) Label(summary_window, text='My Height [cm]').place(relx=0.45, rely=0.36, anchor=CENTER) calculate_BMI = Button(summary_window, text='Calculate my BMI', command=lambda: bmi_calc_patient()) calculate_BMI.place(relx=0.78, rely=0.36, anchor=CENTER) # calculates the BMI based on the user height and weight entries, returns messagebox def bmi_calc_patient(): try: weight = input_weight.get() height = input_height.get() if float(weight) > 0 and float(height) > 0: BMI = float(weight) / ( (float(height) / 100)**2) # standard BMI calculation BMI = int(BMI) if BMI <= 18.5: messagebox.showinfo( "BMI", 'Your BMI is ' + str(BMI) + '. This is underweight, contact your GP.') elif 25.0 < BMI <= 30.0: messagebox.showinfo( "BMI", 'Your BMI is ' + str(BMI) + '. This is overweight.') elif BMI > 30.0: messagebox.showinfo( "BMI", 'Your BMI is ' + str(BMI) + '. This is obese, ask your GP for help.') else: messagebox.showinfo( "BMI", 'Your BMI is ' + str(BMI) + '. This is in the healthy range.') else: messagebox.showinfo("BMI error", 'We do not accept negative input.') logger.error("Incorrect BMI input") except ValueError: messagebox.showinfo("BMI error", 'You have not written a correct input.') logger.error("Incorrect BMI input") except: messagebox.showinfo( "BMI error", 'We are sorry, the function is not working at the moment, try again ' 'later.') logger.error("Incorrect BMI input") # prints GP's entry notes from consultations Label(summary_window, text='Notes from consultations', font=fontStyle2).place(relx=0.5, rely=0.47, anchor=CENTER) full_notes = '' if len(self.notes) > 0: for note in self.notes: # corrects for longer notes than 1 standard line (breaks into max 3 lines) if len(note) > 170: note = note[:170] + '\n' + note[170:] elif len(note) > 340: note = note[:170] + '\n' + note[170:340] + '\n' + note[340:] if len(note) > 510: logger.critical("Too long note to show.") single_note = note + '\n\n' full_notes += single_note else: full_notes = 'Your GP has not uploaded any consultation notes from previous appointments' Label(summary_window, text=full_notes).place(relx=0.5, rely=0.55, anchor=CENTER) Button(summary_window, text='Return', command=lambda: (summary_window.destroy())).place(relx=0.5, rely=0.95, anchor=CENTER)
def prescription(patient): """ Shows patient's precriptions, patient can request prescription that GP has to approve Arguments: json database Returns: updates database (GP has to approve) """ def confirm_request(): db = json.load(open('../uch_system/database.json')) request_list['Reason for request'] = request_box.get( "1.0", 'end-1c') request_date = str(datetime.date.today()) full_request = {request_date: request_list} db[patient.username]['Feedback'].append(full_request) json.dump(db, open('../uch_system/database.json', 'w'), indent=2) meds_window.destroy() messagebox.showinfo("Request", "Your request has been confirmed") def request(): global request_list, request_box meds_window.geometry("800x650") selected = my_tree.selection() request_list = {} print_records = '' if selected == (): messagebox.showwarning( "Problem", "No prescription was selected. Please try again.") return for rec in selected: value = my_tree.item(rec, 'values') print_records += str(value[2]) + " " + str(value[3]) + "\n" request_list[value[2]] = value[3] Label(meds_window, text='Reason for request').grid(row=4, column=0, pady=10, columnspan=2) request_box = Text(meds_window, bg='honeydew2', width=60, height=10) request_box.grid(row=5, column=0, columnspan=2) Label(meds_window, text='Thank you, your GP will have a look at the request and get back to you shortly.') \ .grid(row=6, column=0, columnspan=2) Button(meds_window, text="Confirm Request", command=confirm_request).grid(row=7, column=0, pady=20, columnspan=2) value_label = Label(meds_window, text=print_records) value_label.grid(row=3, column=0, columnspan=2) # Show all of patient's medications meds_window = Tk() meds_window.title('My Prescriptions') meds_window.geometry("800x350") data = json.load(open('../uch_system/database.json')) my_tree = ttk.Treeview(meds_window) # Define columns my_tree['columns'] = ('ID', 'Start Date', 'Name', 'Dosage', 'Quantity', 'Duration (days)', 'Expiry Date') # Format columns my_tree.column("#0", width=0, stretch=NO) my_tree.column("ID", anchor=CENTER, width=80, stretch=NO) my_tree.column("Start Date", anchor=CENTER, width=100) my_tree.column("Name", anchor=W, width=140) my_tree.column("Dosage", anchor=W, width=140) my_tree.column("Quantity", anchor=CENTER, width=80) my_tree.column("Duration (days)", anchor=CENTER, width=100) my_tree.column("Expiry Date", anchor=CENTER, width=100) # Create headings my_tree.heading("#0", text="", anchor=W) my_tree.heading("ID", text="ID", anchor=CENTER) my_tree.heading("Start Date", text="Start Date", anchor=CENTER) my_tree.heading("Name", text="Name", anchor=W) my_tree.heading("Dosage", text="Dosage", anchor=W) my_tree.heading("Quantity", text="Quantity", anchor=CENTER) my_tree.heading("Duration (days)", text="Duration (days)", anchor=CENTER) my_tree.heading("Expiry Date", text="Expiry Date", anchor=CENTER) count = 0 for recs in data.values(): if patient.nhs_number == recs["NHS_number"]: for med in recs['prescriptions']: my_tree.insert(parent='', index='end', iid=count, text="", values=(med['uid'], med['start_date'], med['med_name'], med['dosage'], med['quantity'], med['duration'], med['expiry'])) my_tree.grid(row=0, column=0, columnspan=2, padx=20, pady=10) count += 1 exp = datetime.datetime.strptime(med['expiry'], '%Y-%m-%d').date() now = datetime.date.today() if exp < now: messagebox.showwarning( "EXPIRED", med['med_name'] + " " + med['expiry']) json.dump(data, open('../uch_system/database.json', 'w'), indent=2) request_label = Label(meds_window, text="Medication requests") request_label.grid(row=1, column=0, pady=10, columnspan=2) request_btn = Button(meds_window, text="Request selected medication", command=request) request_btn.grid(row=2, column=0, columnspan=2, pady=10) if count == 0: meds_window.destroy() messagebox.showwarning( "Notice", "You have not been assigned any prescriptions by your GP")
from tkinter import Tk from tank import GAME_TITLE from tank.TankGame import TankGame class TankStart(Tk): def __init__(self): super().__init__() self.title('TankCraft') self.geometry('800x600') if __name__ == '__main__': tank = Tk() tank.title(GAME_TITLE) tankGame = TankGame(master=tank) tankGame.mainloop()
def spaSekmeAc(): window.destroy() spaSekme = Tk() spaSekme.title("Diccionario") spaSekme.geometry("720x480") spaSekme.configure(background="lightgreen") with open('anlamlistspa.txt', 'r') as f: anlamlar = [line.strip() for line in f] def rastdosya(): rastdosya = "kelimelistspa.txt" return rastdosya def rastkel(file_name): global all_words_in_file with open("kelimelistspa.txt", 'r') as f: all_words_in_file = [line.strip() for line in f] global i i = random.randrange(len(all_words_in_file)) random_word = all_words_in_file[i] return random_word def keldeis(): lbl['text'] = rastkel(rastdosya()) if __name__ == '__main__': lbl = tk.Label(spaSekme, font=("TimesNewRoman", 40)) lbl.configure(background="lightgreen") btn = tk.Button(spaSekme, text="Mostrar Palabra!", command=keldeis, font=("TimesNewRoman", 12), height=5) btn.pack(side="bottom", fill=X) def printtext(): global cevap cevap = e.get() if cevap == anlamlar[i]: e.delete(0, "end") str_var.set("Cierto!") else: str_var.set(f"Falso! La respuesta fue {anlamlar[i].upper()}") e.delete(0, "end") str_var = StringVar() str_label = Label(spaSekme, textvariable=str_var, height=3, font=("TimesNewRoman", 30), relief="flat", bg="lightgreen", fg="red") e = Entry(spaSekme, font=("TimesNewRoman", 40)) e.pack(side="bottom") str_label.pack(side="bottom") e.focus_set() lbl.pack(side="bottom") b = Button(spaSekme, text='Revisalo!', command=printtext, font=("TimesNewRoman", 10), height=5) b.pack(side="top", fill=X) spaSekme.bind('<Return>', lambda event=None: b.invoke()) spaSekme.bind('<Shift_L>', lambda event=None: btn.invoke()) spaSekme.mainloop()
from tkinter import Canvas, Tk from re import split bgColor = 'white' main = Tk() c = Canvas(width=1000, height=200, bg=bgColor) c.pack() linka = 'linka3.txt' with open(linka, 'r') as f: color = split('\n', f.readline())[0] x = 10 for line in f: line = split('\n', line)[0] if x == 10: c.create_rectangle(x, 170, x + 10, 180, fill=color) elif line[0] != '*': c.create_oval(x, 170, x + 10, 180, fill=color) else: c.create_oval(x, 170, x + 10, 180, outline=color) c.create_line(x + 10, 175, x + 20, 175, fill=color) c.create_text(x + 10, 170, angle=45, anchor='sw', text=line, font=('Arial',8)) x += 20 c.create_rectangle(x - 20, 170, x - 10, 180, fill=color) c.create_line(x - 10, 175, x, 175, fill=bgColor) main.mainloop()
def engSekmeAc(): window.destroy() engSekme = Tk() engSekme.title("Dictionary") engSekme.geometry("720x480") engSekme.configure(background="lightgreen") anlamlar1 = defaultdict(list) all_words_in_file1 = defaultdict(list) with open('anlamlisteng.txt', 'r') as f: anlamlar1 = [line.strip() for line in f] def rastdosya(): rastdosya = "kelimelisteng.txt" return rastdosya def rastkel(file_name): global all_words_in_file1 with open("kelimelisteng.txt", 'r') as f: all_words_in_file1 = [line.strip() for line in f] global i i = random.randrange(len(all_words_in_file1)) random_word = all_words_in_file1[i] return random_word def keldeis(): lbl['text'] = rastkel(rastdosya()) if __name__ == '__main__': lbl = tk.Label(engSekme, font=("TimesNewRoman", 40)) lbl.configure(background="lightgreen") btn = tk.Button(engSekme, text="Show Word!", command=keldeis, font=("TimesNewRoman", 12), height=5) btn.pack(side="bottom", fill=X) def printtext(): global cevap cevap = e.get() if cevap == anlamlar1[i]: e.delete(0, "end") str_var.set("Correct!") else: str_var.set(f"Mistake! Answer was {anlamlar1[i].upper()}") e.delete(0, "end") str_var = StringVar() str_label = Label(engSekme, textvariable=str_var, height=3, font=("TimesNewRoman", 30), relief="flat", bg="lightgreen", fg="red") e = Entry(engSekme, font=("TimesNewRoman", 40)) e.pack(side="bottom") str_label.pack(side="bottom") e.focus_set() lbl.pack(side="bottom") b = Button(engSekme, text='Check It!', command=printtext, font=("TimesNewRoman", 10), height=5) b.pack(side="top", fill=X) engSekme.bind('<Return>', lambda event=None: b.invoke()) engSekme.bind('<Shift_L>', lambda event=None: btn.invoke()) engSekme.mainloop()
#!/usr/bin/env python # coding: utf-8 # In[1]: import pandas as pd from tkinter import Tk from tkinter.filedialog import askopenfilename from matplotlib import pyplot as plt # In[2]: Tk().withdraw() arquivo = askopenfilename() dados = pd.read_csv(arquivo, delimiter =';',decimal=',') # In[3]: media= dados[["Obs1","Obs2","Obs3","Obs4","Obs5","Obs6"]].mean(axis=1) desvio=dados[["Obs1","Obs2","Obs3","Obs4","Obs5","Obs6"]].std(axis=1) maximo=dados[["Obs1","Obs2","Obs3","Obs4","Obs5","Obs6"]].max(axis=1) minimo=dados[["Obs1","Obs2","Obs3","Obs4","Obs5","Obs6"]].min(axis=1) amplitude=maximo-minimo # In[4]:
c.itemconfigure(cheek_right , state = HIDDEN) c.itemconfigure(mouth_happy , state = HIDDEN) c.itemconfigure(mouth_normal , state = NORMAL) c.itemconfigure(mouth_sad, state = HIDDEN) return def sad(): if c.happy_level == 0 : c.itemconfigure(mouth_happy , state = HIDDEN) c.itemconfigure(mouth_normal , state = HIDDEN) c.itemconfigure(mouth_sad , state = NORMAL) else: c.happy_level -= 1 win.after(500,sad) win=Tk() c=Canvas(win,width=400,height=400) c.configure(bg='darkblue',highlightthickness=0) c.body_color='SkyBlue1' body=c.create_oval(20,50,380,350,fill=c.body_color,outline=c.body_color) foot_left = c.create_oval(65,320,145,360 , outline=c.body_color , fill=c.body_color) foot_right = c.create_oval(255,320,335,360 , outline=c.body_color , fill=c.body_color) ear_left = c.create_polygon(75,100,75,10,165,70,outline=c.body_color , fill=c.body_color) ear_right = c.create_polygon(235,70,325,10,325,100,outline=c.body_color, fill=c.body_color) eye_left = c.create_oval(130,110,160,170,outline='black' , fill='white') pupil_left = c.create_oval(140,145,150,155,outline='black' , fill='black')
def callback(event): global k, entry if entry.get() == "hello": k = True def on_closing(): click(675, 420) moveTo(675, 420) root.attributes("-fullscreen", True) root.protocol("WM_DELETE_WINDOW", on_closing) root.update() root.bind('<Control-KeyPress-c>', callback) root = Tk() # Создание окна root.title("Locker") # Заголовочное название root.attributes("-fullscreen", True) # Расширение под экран entry = Entry(root, font=1) # Поле ввода entry.place(width=150, height=50, x=600, y=400) # Координаты и размеры label0 = Label(root, text="Locker_by_#571", font=1) # Надпись 1 label0.grid(row=0, column=0) # Координаты надписи 1 label1 = Label(root, text="Write the Password and Press Ctrl+C", font='Arial 20') # Надпись 2 label1.place(x=470, y=300) # Координаты надписи 2 root.update() sleep(0.2) click(675, 420) # Обновление экрана программы k = False while k != True:
def __init__(self): self.CalcWindow = Tk() self.CalcWindow.title('Calculator') self.CalcWindow.resizable(False, False) self.CalcWindow.configure(bg='#222831') self.displayframe = Frame(self.CalcWindow, borderwidth=5, relief=SUNKEN) self.displayframe.pack(fil='x', pady=10, padx=10) self.displayframe.configure(bg='#222831') self.entry = Entry(self.displayframe, borderwidth=10, relief=FLAT, font='10', bg='#77abb7', fg='black') self.entry.focus() self.entry.pack(fill='x') self.buttonframe = Frame(self.CalcWindow) self.buttonframe.pack(fill='x', padx=30, pady=30) self.buttonframe.configure(bg='#222831') self.colorsCombs = [('#e84a5f', '#ff847c'), ('#3f4441', '#5e6f64'), ('#87d4c5', '#2bb2bb'), ('#436f8a', '#438a5e'), ('#10375c', '#127681')] self.primarycolor = self.colorsCombs[random.randrange(0, 5)][0] self.secondarycolor = self.colorsCombs[random.randrange(0, 5)][1] self.button8 = Button(self.buttonframe, text='8', width=5, height=2, bg=self.primarycolor, font='5', fg='white', activebackground='green', command=lambda: self.addchar(8)) self.button9 = Button(self.buttonframe, text='9', width=5, height=2, bg=self.primarycolor, font='5', fg='white', activebackground='green', command=lambda: self.addchar(9)) self.button7 = Button(self.buttonframe, text='7', width=5, height=2, bg=self.primarycolor, font='5', fg='white', activebackground='green', command=lambda: self.addchar(7)) self.button4 = Button(self.buttonframe, text='4', width=5, height=2, bg=self.primarycolor, font='5', fg='white', activebackground='green', command=lambda: self.addchar(4)) self.button5 = Button(self.buttonframe, text='5', width=5, height=2, bg=self.primarycolor, font='5', fg='white', activebackground='green', command=lambda: self.addchar(5)) self.button6 = Button(self.buttonframe, text='6', width=5, height=2, bg=self.primarycolor, font='5', fg='white', activebackground='green', command=lambda: self.addchar(6)) self.button1 = Button(self.buttonframe, text='1', width=5, height=2, bg=self.primarycolor, font='5', fg='white', activebackground='green', command=lambda: self.addchar(1)) self.button2 = Button(self.buttonframe, text='2', width=5, height=2, bg=self.primarycolor, font='5', fg='white', activebackground='green', command=lambda: self.addchar(2)) self.button3 = Button(self.buttonframe, text='3', width=5, height=2, bg=self.primarycolor, font='5', fg='white', activebackground='green', command=lambda: self.addchar(3)) self.buttondot = Button(self.buttonframe, text='.', width=5, height=2, bg=self.secondarycolor, font='5', fg='white', activebackground='green', command=lambda: self.addchar('.')) self.button0 = Button(self.buttonframe, text='0', width=5, height=2, bg=self.primarycolor, font='5', fg='white', activebackground='green', command=lambda: self.addchar(0)) self.buttondiv = Button(self.buttonframe, text='/', width=5, height=2, bg=self.secondarycolor, font='5', fg='white', activebackground='green', command=lambda: self.addchar('/')) self.buttonmul = Button(self.buttonframe, text='*', width=5, height=2, bg=self.secondarycolor, font='5', fg='white', activebackground='green', command=lambda: self.addchar('*')) self.buttonmin = Button(self.buttonframe, text='-', width=5, height=2, bg=self.secondarycolor, font='5', fg='white', activebackground='green', command=lambda: self.addchar('-')) self.buttonadd = Button(self.buttonframe, text='+', width=5, height=2, bg=self.secondarycolor, font='5', fg='white', activebackground='green', command=lambda: self.addchar('+')) self.buttonback = Button(self.buttonframe, text='C', width=5, height=2, bg=self.secondarycolor, font='5', fg='white', activebackground='green', command=lambda: self.backspace()) self.buttoneql = Button(self.buttonframe, text='=', width=5, height=2, bg=self.secondarycolor, font='5', fg='white', activebackground='green', command=self.sum) self.buttondel = Button(self.buttonframe, text='CLR', width=5, height=2, bg=self.secondarycolor, font='5', fg='white', activebackground='green', command=lambda: self.clear()) self.buttonlb = Button(self.buttonframe, text='(', width=5, height=2, bg=self.secondarycolor, font='5', fg='white', activebackground='green', command=lambda: self.addchar('(')) self.buttonrb = Button(self.buttonframe, text=')', width=5, height=2, bg=self.secondarycolor, font='5', fg='white', activebackground='green', command=lambda: self.addchar(')')) self.button7.grid(row=0, column=0, padx=5, pady=5) self.button8.grid(row=0, column=1, padx=5, pady=5) self.button9.grid(row=0, column=2, padx=5, pady=5) self.button4.grid(row=1, column=0, padx=5, pady=5) self.button5.grid(row=1, column=1, padx=5, pady=5) self.button6.grid(row=1, column=2, padx=5, pady=5) self.button1.grid(row=2, column=0, padx=5, pady=5) self.button2.grid(row=2, column=1, padx=5, pady=5) self.button3.grid(row=2, column=2, padx=5, pady=5) self.buttondot.grid(row=3, column=0, padx=5, pady=5) self.button0.grid(row=3, column=1, padx=5, pady=5) self.buttondiv.grid(row=0, column=3, padx=5, pady=5) self.buttonmul.grid(row=1, column=3, padx=5, pady=5) self.buttonmin.grid(row=2, column=3, padx=5, pady=5) self.buttonadd.grid(row=3, column=3, padx=5, pady=5) self.buttonback.grid(row=4, column=0, padx=5, pady=5) self.buttoneql.grid(row=3, column=2, padx=5, pady=5) self.buttondel.grid(row=4, column=1, padx=5, pady=5) self.buttonlb.grid(row=4, column=2, padx=5, pady=5) self.buttonrb.grid(row=4, column=3, padx=5, pady=5)
# Failed from tkinter import Tk, Label, Entry, Button, TOP import pymysql cursor = pymysql.connect(host="localhost", user="******", passwd="123456").cursor() # 初始化数据库连接 cursor.execute("use testdb") root = Tk() # 初始化窗口 root.title("QR Code Generator") root.geometry("800x600") def register(): pass lab1 = Label(root, text="请输入名字:", font=("微软雅黑", 18)) inp = Entry(root, width=50) but = Button(root, text="注册", font=("微软雅黑", 18), command=register) lab1.pack(side=TOP) inp.pack(side=TOP) but.pack(side=TOP) root.mainloop()
class Stitcher: _root = Tk() _root.withdraw() # Use TK to ask and set working directory def ask_for_dir(self): dir_selected = filedialog.askdirectory() self.set_wdir(dir_selected) # Function to set working directory def set_wdir(self, dir): self._wdir = dir # Find and set main tlog file def find_tlog(self): for filename in os.listdir(self._wdir): if filename.endswith(".tlog"): self.set_tlog(os.path.join(self._wdir, filename)) break # Set main tlog file def set_tlog(self, file): self._tlog = file # Main solve func def solve(self): self.find_tlog() print("creating canvas...") canvas = Image.new("RGBA", (CANVAS_SIZE, CANVAS_SIZE), (0, 0, 0, 0)) print("finished creating canvas...") mlog = mavutil.mavlink_connection(self._tlog) data = [] i = 0 while True: m = mlog.recv_match(type=["CAMERA_FEEDBACK"]) if m is None: break data.append(m.to_dict()) dx, dy = 0, 0 for i in range(len(data)): target_photo_path = None idata = data[i] photo_id = '{0:03d}'.format(idata["img_idx"]) """ ОСОБЕННО ТУТ НИЧЕГО НЕ ТРОГАТЬ """ lat = idata["lat"] // 75 lng = idata["lng"] // 75 if idata["img_idx"] == 1: dy, dx = abs(CANVAS_SIZE // 2 - lat), abs(CANVAS_SIZE // 10 - lng) print("dx, dy: ", dx, dy) py, px = lat - dy, lng - dx #if not (photo_id == "055" or photo_id == "056" or photo_id == "057"): # continue for filename in os.listdir(self._wdir): if filename.endswith(photo_id + ".JPG"): target_photo_path = os.path.join(self._wdir, filename) break if target_photo_path == None: print("skipping photo") continue target_photo = Image.open(target_photo_path).convert( "RGBA").rotate(idata["yaw"] - 180, expand=1).resize( (600, 450), Image.ANTIALIAS) print("id: ", photo_id) print("px, py: ", px, py) print("pasting image #{}".format(photo_id)) canvas.paste(target_photo, (px, py), target_photo) canvas.show()
def __init__(self): if db.authenticated: if db.channel == "Development": response = requests.get( "http://div0ky.com/repo/development/latest.txt") elif db.channel == "Staging": response = requests.get( "http://div0ky.com/repo/staging/latest.txt") else: response = requests.get( "http://div0ky.com/repo/stable/latest.txt") latest = response.text print( f"Current Version is {current_version}\nLatest Version is {latest}" ) if semver.compare(latest, current_version) > 0: root = Tk() root.withdraw() ask_update = messagebox.askyesno( title=f"FIB v{current_version}", message= f"A new version is availble. You're running v{current_version}. The latest version is v{latest}.\n\nDo you want to download & update?", parent=root) root.destroy() if ask_update: update = f"http://div0ky.com/repo/Firestone_Bot_v{latest}.exe" with open( os.getenv('LOCALAPPDATA') + f"/Firestone Idle Bot/Firestone_Bot_v{latest}.exe", 'wb') as f: response = requests.get(update, stream=True) total_size = response.headers.get('content-length') if total_size is None: f.write(response.content) else: dl = 0 total_size = int(total_size) adj_size = round(int(total_size) / 1000, 2) for data in response.iter_content(chunk_size=4096): dl += int(len(data)) adj_dl = round(dl / 1000, 2) f.write(data) done = int(100 * dl / total_size) db.launch_progress = done db.launch_text = f"{adj_dl}KB / {adj_size}KB" if not db.launch_running: break # print("\r[%s%s]" % ('=' * done, ' ' * (50 - done))) if db.launch_running: db.launch_text = "DOWNLOAD COMPLETE" # messagebox.showinfo(title="DOWNLOAD COMPLETE", message="Download Complete. Launching Installer...") if db.launch_running: log.info(f"Updated to v{latest}") os.startfile( os.getenv('LOCALAPPDATA') + f"/Firestone Idle Bot/Firestone_Bot_v{latest}.exe") sys.exit() else: db.updater_finished = True
from tkinter import Tk from src.alumnifinder.gui.app import App root = Tk() # initializes tkinter app = App( root ) # creates window with bar and decorations specified by window manager root.mainloop() # makes window appear
from tkinter import Tk, Canvas, Label glavni = Tk() c1 = Canvas(glavni, bg="blue", height=200, width=200) c1.pack(side="right", expand=1, fill="both") c2 = Canvas(glavni, bg="red", height=200, width=200) c2.pack(side="right", expand=1, fill="both") c3 = Canvas(glavni, bg="green", height=200, width=400) c3.pack(side="left", expand=1, fill="both") c4 = Canvas(glavni, bg="yellow", height=200, width=200) c4.pack(side="bottom", expand=1, fill="both") oznaka = Label(c1, text="Ime osobe:", relief="raised") oznaka.pack() glavni.mainloop()
res = chatbot_response(msg) ChatLog.insert(END, 'Bot: ' + res + '\n\n') ChatLog.config(state=DISABLED) ChatLog.yview(END) if __name__ == '__main__': lemmatizer = WordNetLemmatizer() model = load_model('chatbot_model.h5') intents = json.loads(open('intents.json').read()) words = pickle.load(open('words.pkl', 'rb')) classes = pickle.load(open('classes.pkl', 'rb')) base = Tk() base.title('Hello') base.geometry('400x500') base.resizable(width=FALSE, height=FALSE) ChatLog = Text(base) ChatLog.config(state=DISABLED) scrollbar = Scrollbar(base) ChatLog['yscrollcommand'] = scrollbar.set SendButton = Button(base, text='Send', command=send) EntryBox = Text(base) scrollbar.place(x=376, y=6, height=386)
def setUpModule(): global root, dialog idleConf.userCfg = testcfg root = Tk() # root.withdraw() # Comment out, see issue 30870 dialog = configdialog.ConfigDialog(root, 'Test', _utest=True)
def __init__(self): self.args = parse_args() cfg = mmcv.Config.fromfile(self.args.config) self.window = Tk() self.menubar = Menu(self.window) self.info = StringVar() self.info_label = Label( self.window, bg='yellow', width=4, textvariable=self.info) self.listBox_img = Listbox( self.window, width=50, height=25, font=('Times New Roman', 10)) self.listBox_obj = Listbox( self.window, width=50, height=12, font=('Times New Roman', 10)) self.scrollbar_img = Scrollbar( self.window, width=15, orient='vertical') self.scrollbar_obj = Scrollbar( self.window, width=15, orient='vertical') self.listBox_img_info = StringVar() self.listBox_img_label = Label( self.window, font=('Arial', 11), bg='yellow', width=4, height=1, textvariable=self.listBox_img_info) self.listBox_obj_info = StringVar() self.listBox_obj_label1 = Label( self.window, font=('Arial', 11), bg='yellow', width=4, height=1, textvariable=self.listBox_obj_info) self.listBox_obj_label2 = Label( self.window, font=('Arial', 11), bg='yellow', width=4, height=1, text='Object Class : Score (IoU)') if cfg.dataset_type == 'VOCDataset': self.data_info = VOC_dataset(cfg, self.args) elif cfg.dataset_type == 'CocoDataset': self.data_info = COCO_dataset(cfg, self.args) self.info.set('DATASET: {}'.format(self.data_info.dataset)) # load image and show it on the window self.img = self.data_info.get_img_by_index(0) self.photo = ImageTk.PhotoImage(self.img) self.label_img = Label(self.window, image=self.photo) self.show_det_txt = IntVar(value=1) self.checkbn_det_txt = Checkbutton( self.window, text='Text', font=('Arial', 10, 'bold'), variable=self.show_det_txt, command=self.change_img, fg='#0000FF') self.show_dets = IntVar(value=1) self.checkbn_det = Checkbutton( self.window, text='Detections', font=('Arial', 10, 'bold'), variable=self.show_dets, command=self.change_img, fg='#0000FF') self.show_gt_txt = IntVar(value=1) self.checkbn_gt_txt = Checkbutton( self.window, text='Text', font=('Arial', 10, 'bold'), variable=self.show_gt_txt, command=self.change_img, fg='#FF8C00') self.show_gts = IntVar(value=1) self.checkbn_gt = Checkbutton( self.window, text='Groundtruth', font=('Arial', 10, 'bold'), variable=self.show_gts, command=self.change_img, fg='#FF8C00') self.combo_label = Label( self.window, bg='yellow', width=10, height=1, text='Show Category', font=('Arial', 11)) self.combo_category = ttk.Combobox( self.window, font=('Arial', 11), values=self.data_info.aug_category.combo_list) self.combo_category.current(0) self.th_label = Label( self.window, font=('Arial', 11), bg='yellow', width=10, height=1, text='Score Threshold') self.threshold = np.float32(0.5) self.th_entry = Entry( self.window, font=('Arial', 11), width=10, textvariable=StringVar(self.window, value=str(self.threshold))) self.th_button = Button( self.window, text='Enter', height=1, command=self.change_threshold) self.iou_th_label = Label( self.window, font=('Arial', 11), bg='yellow', width=10, height=1, text='IoU Threshold') self.iou_threshold = np.float32(0.5) self.iou_th_entry = Entry( self.window, font=('Arial', 11), width=10, textvariable=StringVar(self.window, value=str(self.iou_threshold))) self.iou_th_button = Button( self.window, text='Enter', height=1, command=self.change_iou_threshold) self.find_label = Label( self.window, font=('Arial', 11), bg='yellow', width=10, height=1, text='find') self.find_name = '' self.find_entry = Entry( self.window, font=('Arial', 11), width=10, textvariable=StringVar(self.window, value=str(self.find_name))) self.find_button = Button( self.window, text='Enter', height=1, command=self.findname) self.listBox_img_idx = 0 # ====== ohter attribute ====== self.img_name = '' self.show_img = None self.output = self.args.output if not os.path.isdir(self.output): os.makedirs(self.output) self.img_list = self.data_info.img_list # flag for find/threshold button switch focused element self.button_clicked = False