class GuiGenerateCount(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.pack() #step increment len self._stepLenFrm = Frame(self); self._stepLenFrm.pack() self._stepLenLbl = Label(self._stepLenFrm, text="Step Len: "); self._stepLenLbl.pack(side=LEFT) self._stepLenSpin = Spinbox(self._stepLenFrm, from_=0, to=1000); self._stepLenSpin.pack(side=LEFT) #start value self._startFrm = Frame(self); self._startFrm.pack() self._startLbl = Label(self._startFrm, text="Start Value: "); self._startLbl.pack(side=LEFT) self._startTxt = Entry(self._startFrm); self._startTxt.pack(side=LEFT) self._startTxt.insert(0, "0") def getSettings(self): return { "StepLen": self._stepLenSpin.get(), "StartValue": self._startTxt.get() } def getName(self): return "Counter" def getGeneratorFunction(self): return generateCounter
def create_widgets(self, clear_all_fnc): ''' Creates widgets of this frame. Args: clear_all_fnc (function): function that should be called when "Clear all" button is pressed. ''' rows_spinbox = Spinbox(self, from_=1, to=100, width=3, textvariable=self.row_str_var) rows_spinbox.grid(row=0, column=0, pady=3, padx=3) add_row_btn = Button(self, text='Add row(s)', command=self.add_rows) add_row_btn.grid(row=0, column=1, sticky=N+E+W, pady=3) remove_row_btn = Button(self, text='Remove row(s)', command=self.remove_rows) remove_row_btn.grid(row=1, column=1, sticky=N+E+W, pady=3) columns_spinbox = Spinbox(self, from_=1, to=100, width=3, textvariable=self.col_str_var) columns_spinbox.grid(row=2, column=0, pady=3, padx=3) add_column_btn = Button(self, text='Add column(s)', command=self.add_columns) add_column_btn.grid(row=2, column=1, sticky=N+E+W, pady=3) remove_column_btn = Button(self, text='Remove column(s)', command=self.remove_columns) remove_column_btn.grid(row=3, column=1, sticky=N+E+W, pady=3) clear_all_btn = Button(self, text='Clear all', command=clear_all_fnc) clear_all_btn.grid(row=4, column=1, sticky=N+E+W, pady=3)
def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.pack() #step increment len self._stepLenFrm = Frame(self); self._stepLenFrm.pack() self._stepLenLbl = Label(self._stepLenFrm, text="Step Len: "); self._stepLenLbl.pack(side=LEFT) self._stepLenSpin = Spinbox(self._stepLenFrm, from_=0, to=1000); self._stepLenSpin.pack(side=LEFT) #start value self._startFrm = Frame(self); self._startFrm.pack() self._startLbl = Label(self._startFrm, text="Start Value: "); self._startLbl.pack(side=LEFT) self._startTxt = Entry(self._startFrm); self._startTxt.pack(side=LEFT) self._startTxt.insert(0, "0")
def create_widgets(self): ''' Creates all necessary widgets for navigation. ''' prev_btn = Button(self, text='<<', width=5, command=self.show_prev_page) prev_btn.grid(row=0, column=0, sticky=N, padx=3) next_btn = Button(self, text='>>', width=5, command=self.show_next_page) next_btn.grid(row=0, column=1, sticky=N) goto_lbl = Label(self, text='Go to') goto_lbl.grid(row=0, column=3, sticky=N, padx=5) self.goto_spin = Spinbox(self, width=7, from_=1, to=1, textvariable=self.current_page_str, command=self.on_page_change) self.goto_spin.bind('<Return>', self.on_page_change) self.goto_spin.grid(row=0, column=4, sticky=N, padx=5) nb_pages_lb = Label(self, textvariable=self.text_var_nb_pages) nb_pages_lb.grid(row=0, column=5, sticky=W+N, padx=5) self.reset_navigation()
# Spinbox callback def _spin(): value = spin.get() # print(value) scr.insert(tk.INSERT, value + '\n') def _spin2(): value = spin2.get() # print(value) scr.insert(tk.INSERT, value + '\n') # Adding 2 Spinbox widget using a set of values spin = Spinbox(monty, from_=10, to=25, width=5, bd=8, command=_spin) spin.grid(column=0, row=2) spin2 = Spinbox(monty, values=('Python3入门', 'C语言', 'C++', 'Java', 'OpenCV'), width=13, bd=3, command=_spin2) spin2.grid(column=1, row=2, sticky='W') # Using a scrolled Text control scrolW = 30; scrolH = 5 scr = scrolledtext.ScrolledText(monty, width=scrolW, height=scrolH, wrap=tk.WORD) scr.grid(column=0, row=3, sticky='WE', columnspan=3) # Add Tooltip createToolTip(spin, '这是一个Spinbox.') createToolTip(spin2, '这是一个Spinbox.') createToolTip(action, '这是一个Button.')
number = tk.StringVar() numberChosen = ttk.Combobox(monty, width=12, textvariable=number) numberChosen['values'] = (1, 2, 4, 42, 100) numberChosen.grid(column=1, row=1) numberChosen.current(0) # Spinbox callback def _spin(): value = spin.get() print(value) scr.insert(tk.INSERT, value + '\n') # Adding a Spinbox widget using a set of values spin = Spinbox(monty, values=(1, 2, 4, 42, 100), width=5, bd=8, command=_spin) spin.grid(column=0, row=2) # Add a Tooltip createToolTip(spin, 'This is a Spin control.') # Using a scrolled Text control scrolW = 30 scrolH = 3 scr = scrolledtext.ScrolledText(monty, width=scrolW, height=scrolH, wrap=tk.WORD) scr.grid(column=0, row=3, sticky='WE', columnspan=3) createToolTip(scr, 'This is a Scroll control.')
div = Label( root, bg="#0a0b11", ) div.grid(row=3, column=0) Label(div, text="Dp", bg="#0a0b11", fg="white", justify="left").grid(row=0, column=0) Spinbox(div, from_=1, to=2, textvariable=a_dp, bg="white", fg="black", bd=0, width=5, wrap=True, justify="left").grid(row=0, column=1) Label(div, text="minDist", bg="#0a0b11", fg="white", justify="left").grid(row=1, column=0) Spinbox(div, textvariable=a_minDist, bg="white", fg="black", bd=0, width=5, wrap=True,
class OOP(): def __init__(self): # Create instance self.win = tk.Tk() self.i18n = I18N('en') self.i18n = I18N('de') # Add a title self.win.title(self.i18n.title) # Disable resizing the window self.win.resizable(0, 0) # Create a Queue self.guiQueue = Queue() self.createWidgets() # populate Tab 2 Entries self.defaultFileEntries() # create MySQL instance self.mySQL = MySQL() def defaultFileEntries(self): self.fileEntry.delete(0, tk.END) self.fileEntry.insert(0, 'Z:\\') # bogus path self.fileEntry.config(state='readonly') self.netwEntry.delete(0, tk.END) self.netwEntry.insert(0, 'Z:\\Backup') # bogus path # Combobox callback def _combo(self, val=0): value = self.combo.get() self.scr.insert(tk.INSERT, value + '\n') # Spinbox callback def _spin(self): value = self.spin.get() self.scr.insert(tk.INSERT, value + '\n') # Checkbox callback def checkCallback(self, *ignoredArgs): # only enable one checkbutton if self.chVarUn.get(): self.check3.configure(state='disabled') else: self.check3.configure(state='normal') if self.chVarEn.get(): self.check2.configure(state='disabled') else: self.check2.configure(state='normal') # Radiobutton callback function def radCall(self): radSel = self.radVar.get() if radSel == 0: self.widgetFrame.configure(text=self.i18n.WIDGET_LABEL + self.i18n.colorsIn[0]) elif radSel == 1: self.widgetFrame.configure(text=self.i18n.WIDGET_LABEL + self.i18n.colorsIn[1]) elif radSel == 2: self.widgetFrame.configure(text=self.i18n.WIDGET_LABEL + self.i18n.colorsIn[2]) # Exit GUI cleanly def _quit(self): self.win.quit() self.win.destroy() exit() def methodInAThread(self, numOfLoops=10): for idx in range(numOfLoops): sleep(1) self.scr.insert(tk.INSERT, str(idx) + '\n') sleep(1) print('methodInAThread():', self.runT.isAlive()) # Running methods in Threads def createThread(self, num): self.runT = Thread(target=self.methodInAThread, args=[num]) self.runT.setDaemon(True) self.runT.start() print(self.runT) print('createThread():', self.runT.isAlive()) # textBoxes are the Consumers of Queue data writeT = Thread(target=self.useQueues, daemon=True) writeT.start() # Create Queue instance def useQueues(self): # Now using a class member Queue while True: qItem = self.guiQueue.get() print(qItem) self.scr.insert(tk.INSERT, qItem + '\n') # Button callback def insertQuote(self): title = self.bookTitle.get() page = self.pageNumber.get() quote = self.quote.get(1.0, tk.END) print(title) print(quote) self.mySQL.insertBooks(title, page, quote) # Button callback def getQuote(self): allBooks = self.mySQL.showBooks() print(allBooks) self.quote.insert(tk.INSERT, allBooks) # Button callback def modifyQuote(self): raise NotImplementedError( "This still needs to be implemented for the SQL command.") # TZ Button callback def allTimeZones(self): for tz in all_timezones: self.scr.insert(tk.INSERT, tz + '\n') # TZ Local Button callback def localZone(self): from tzlocal import get_localzone self.scr.insert(tk.INSERT, get_localzone()) # Format local US time with TimeZone info def getDateTime(self): fmtStrZone = "%Y-%m-%d %H:%M:%S %Z%z" # Get Coordinated Universal Time utc = datetime.now(timezone('UTC')) print(utc.strftime(fmtStrZone)) # Convert UTC datetime object to Los Angeles TimeZone la = utc.astimezone(timezone('America/Los_Angeles')) print(la.strftime(fmtStrZone)) # Convert UTC datetime object to New York TimeZone ny = utc.astimezone(timezone('America/New_York')) print(ny.strftime(fmtStrZone)) # update GUI label with NY Time and Zone self.lbl2.set(ny.strftime(fmtStrZone)) ##################################################################################### def createWidgets(self): # Tab Control introduced here -------------------------------------- tabControl = ttk.Notebook(self.win) # Create Tab Control tab1 = ttk.Frame(tabControl) # Create a tab # tabControl.add(tab1, text='MySQL') # Add the tab -- COMMENTED OUT FOR CH08 tab2 = ttk.Frame(tabControl) # Add a second tab tabControl.add(tab2, text='Widgets') # Make second tab visible tabControl.pack(expand=1, fill="both") # Pack to make visible # ~ Tab Control introduced here ----------------------------------------- # We are creating a container frame to hold all other widgets self.mySQL = ttk.LabelFrame(tab1, text=' Python Database ') self.mySQL.grid(column=0, row=0, padx=8, pady=4) # Creating a Label ttk.Label(self.mySQL, text="Book Title:").grid(column=0, row=0, sticky='W') # Adding a Textbox Entry widget book = tk.StringVar() self.bookTitle = ttk.Entry(self.mySQL, width=34, textvariable=book) self.bookTitle.grid(column=0, row=1, sticky='W') # Adding a Textbox Entry widget book1 = tk.StringVar() self.bookTitle1 = ttk.Entry(self.mySQL, width=34, textvariable=book1) self.bookTitle1.grid(column=0, row=2, sticky='W') # Adding a Textbox Entry widget book2 = tk.StringVar() self.bookTitle2 = ttk.Entry(self.mySQL, width=34, textvariable=book2) self.bookTitle2.grid(column=0, row=3, sticky='W') # Creating a Label ttk.Label(self.mySQL, text="Page:").grid(column=1, row=0, sticky='W') # Adding a Textbox Entry widget page = tk.StringVar() self.pageNumber = ttk.Entry(self.mySQL, width=6, textvariable=page) self.pageNumber.grid(column=1, row=1, sticky='W') # Adding a Textbox Entry widget page = tk.StringVar() self.pageNumber1 = ttk.Entry(self.mySQL, width=6, textvariable=page) self.pageNumber1.grid(column=1, row=2, sticky='W') # Adding a Textbox Entry widget page = tk.StringVar() self.pageNumber2 = ttk.Entry(self.mySQL, width=6, textvariable=page) self.pageNumber2.grid(column=1, row=3, sticky='W') # Adding a Button self.action = ttk.Button(self.mySQL, text="Insert Quote", command=self.insertQuote) self.action.grid(column=2, row=1) # Adding a Button self.action1 = ttk.Button(self.mySQL, text="Get Quotes", command=self.getQuote) self.action1.grid(column=2, row=2) # Adding a Button self.action2 = ttk.Button(self.mySQL, text="Mody Quote", command=self.modifyQuote) self.action2.grid(column=2, row=3) # Add some space around each widget for child in self.mySQL.winfo_children(): child.grid_configure(padx=2, pady=4) quoteFrame = ttk.LabelFrame(tab1, text=' Book Quotation ') quoteFrame.grid(column=0, row=1, padx=8, pady=4) # Using a scrolled Text control quoteW = 40 quoteH = 6 self.quote = scrolledtext.ScrolledText(quoteFrame, width=quoteW, height=quoteH, wrap=tk.WORD) self.quote.grid(column=0, row=8, sticky='WE', columnspan=3) # Add some space around each widget for child in quoteFrame.winfo_children(): child.grid_configure(padx=2, pady=4) #====================================================================================================== # Tab Control 2 #====================================================================================================== # We are creating a container frame to hold all other widgets -- Tab2 self.widgetFrame = ttk.LabelFrame(tab2, text=self.i18n.WIDGET_LABEL) self.widgetFrame.grid(column=0, row=0, padx=8, pady=4) # Creating three checkbuttons self.chVarDis = tk.IntVar() self.check1 = tk.Checkbutton(self.widgetFrame, text=self.i18n.disabled, variable=self.chVarDis, state='disabled') self.check1.select() self.check1.grid(column=0, row=0, sticky=tk.W) self.chVarUn = tk.IntVar() self.check2 = tk.Checkbutton(self.widgetFrame, text=self.i18n.unChecked, variable=self.chVarUn) self.check2.deselect() self.check2.grid(column=1, row=0, sticky=tk.W) self.chVarEn = tk.IntVar() self.check3 = tk.Checkbutton(self.widgetFrame, text=self.i18n.toggle, variable=self.chVarEn) self.check3.deselect() self.check3.grid(column=2, row=0, sticky=tk.W) # trace the state of the two checkbuttons self.chVarUn.trace( 'w', lambda unused0, unused1, unused2: self.checkCallback()) self.chVarEn.trace( 'w', lambda unused0, unused1, unused2: self.checkCallback()) # Radiobutton list colors = self.i18n.colors self.radVar = tk.IntVar() # Selecting a non-existing index value for radVar self.radVar.set(99) # Creating all three Radiobutton widgets within one loop for col in range(3): curRad = 'rad' + str(col) curRad = tk.Radiobutton(self.widgetFrame, text=colors[col], variable=self.radVar, value=col, command=self.radCall) curRad.grid(column=col, row=6, sticky=tk.W, columnspan=3) # And now adding tooltips tt.createToolTip(curRad, 'This is a Radiobutton control.') # Create a container to hold labels labelsFrame = ttk.LabelFrame(self.widgetFrame, text=self.i18n.labelsFrame) labelsFrame.grid(column=0, row=7, pady=6) # Place labels into the container element - vertically ttk.Label(labelsFrame, text=self.i18n.chooseNumber).grid(column=0, row=0) self.lbl2 = tk.StringVar() self.lbl2.set(self.i18n.label2) ttk.Label(labelsFrame, textvariable=self.lbl2).grid(column=0, row=1) # Add some space around each label for child in labelsFrame.winfo_children(): child.grid_configure(padx=6, pady=1) number = tk.StringVar() self.combo = ttk.Combobox(self.widgetFrame, width=12, textvariable=number) self.combo['values'] = (1, 2, 4, 42, 100) self.combo.grid(column=1, row=7, sticky=tk.W) self.combo.current(0) self.combo.bind('<<ComboboxSelected>>', self._combo) # Adding a Spinbox widget using a set of values self.spin = Spinbox(self.widgetFrame, values=(1, 2, 4, 42, 100), width=5, bd=8, command=self._spin) self.spin.grid(column=2, row=7, sticky='W,', padx=6, pady=1) # Using a scrolled Text control scrolW = 40 scrolH = 1 self.scr = scrolledtext.ScrolledText(self.widgetFrame, width=scrolW, height=scrolH, wrap=tk.WORD) self.scr.grid(column=0, row=8, sticky='WE', columnspan=3) # Adding a TZ Button self.allTZs = ttk.Button(self.widgetFrame, text=self.i18n.timeZones, command=self.allTimeZones) self.allTZs.grid(column=0, row=9, sticky='WE') # Adding local TZ Button self.localTZ = ttk.Button(self.widgetFrame, text=self.i18n.localZone, command=self.localZone) self.localTZ.grid(column=1, row=9, sticky='WE') # Adding getTime TZ Button self.dt = ttk.Button(self.widgetFrame, text=self.i18n.getTime, command=self.getDateTime) self.dt.grid(column=2, row=9, sticky='WE') # Create Manage Files Frame ------------------------------------------------ mngFilesFrame = ttk.LabelFrame(tab2, text=self.i18n.mgrFiles) mngFilesFrame.grid(column=0, row=1, sticky='WE', padx=10, pady=5) # Button Callback def getFileName(): print('hello from getFileName') fDir = path.dirname(__file__) fName = fd.askopenfilename(parent=self.win, initialdir=fDir) print(fName) self.fileEntry.config(state='enabled') self.fileEntry.delete(0, tk.END) self.fileEntry.insert(0, fName) if len(fName) > self.entryLen: self.fileEntry.config(width=len(fName) + 3) # Add Widgets to Manage Files Frame lb = ttk.Button(mngFilesFrame, text=self.i18n.browseTo, command=getFileName) lb.grid(column=0, row=0, sticky=tk.W) #----------------------------------------------------- file = tk.StringVar() self.entryLen = scrolW - 4 self.fileEntry = ttk.Entry(mngFilesFrame, width=self.entryLen, textvariable=file) self.fileEntry.grid(column=1, row=0, sticky=tk.W) #----------------------------------------------------- logDir = tk.StringVar() self.netwEntry = ttk.Entry(mngFilesFrame, width=self.entryLen, textvariable=logDir) self.netwEntry.grid(column=1, row=1, sticky=tk.W) def copyFile(): import shutil src = self.fileEntry.get() file = src.split('/')[-1] dst = self.netwEntry.get() + '\\' + file try: shutil.copy(src, dst) mBox.showinfo('Copy File to Network', 'Succes: File copied.') except FileNotFoundError as err: mBox.showerror('Copy File to Network', '*** Failed to copy file! ***\n\n' + str(err)) except Exception as ex: mBox.showerror('Copy File to Network', '*** Failed to copy file! ***\n\n' + str(ex)) cb = ttk.Button(mngFilesFrame, text=self.i18n.copyTo, command=copyFile) cb.grid(column=0, row=1, sticky=tk.E) # Add some space around each label for child in mngFilesFrame.winfo_children(): child.grid_configure(padx=6, pady=6) # Creating a Menu Bar ========================================================== menuBar = Menu(tab1) self.win.config(menu=menuBar) # Add menu items fileMenu = Menu(menuBar, tearoff=0) fileMenu.add_command(label=self.i18n.new) fileMenu.add_separator() fileMenu.add_command(label=self.i18n.exit, command=self._quit) menuBar.add_cascade(label=self.i18n.file, menu=fileMenu) # Add another Menu to the Menu Bar and an item helpMenu = Menu(menuBar, tearoff=0) helpMenu.add_command(label=self.i18n.about) menuBar.add_cascade(label=self.i18n.help, menu=helpMenu) # Change the main windows icon self.win.iconbitmap(r'C:\Python34\DLLs\pyc.ico') # Using tkinter Variable Classes strData = tk.StringVar() strData.set('Hello StringVar') # It is not necessary to create a tk.StringVar() strData = tk.StringVar() strData = self.spin.get() # Place cursor into name Entry self.bookTitle.focus() # Add a Tooltip to the Spinbox tt.createToolTip(self.spin, 'This is a Spin control.') # Add Tooltips to more widgets tt.createToolTip(self.bookTitle, 'This is an Entry control.') tt.createToolTip(self.action, 'This is a Button control.') tt.createToolTip(self.scr, 'This is a ScrolledText control.')
def refreshWidget(self) : #print "refresh" self.card_win.pack_forget() import unicodedata #Card window self.card_win = PanedWindow(self.card_win.master, orient=VERTICAL) self.card_win.pack(side=TOP, expand=True, fill=BOTH, pady=2, padx=2) #Create the name zone name_zone=PanedWindow(self.card_win, orient=HORIZONTAL) name = StringVar() name.set(self.name) def modifName(*args) : try : assert('"' not in name.get()) name.get().encode('ascii') except Exception as e: print ("error on name") name.set(self.name) return old = self.name in Card.blocked_creature self.name=name.get() if old or self.name in Card.blocked_creature : self.refreshWidget() name.trace("w", modifName) name_wid=Entry(name_zone, width=30,textvariable=name) name_wid.pack() name_zone.add(name_wid) #Create the cost ad star stringvar #print int(floor(self.getCost())) self.cost=StringVar() self.stars=StringVar() cost_wid=Label(None, textvariable=self.cost, background='red',width=5, anchor=W) star_wid=Label(None, textvariable=self.stars, background='blue', anchor=E) self.cost.set(str(int(floor(self.getCost())))) self.stars.set("*"*self.getStars()) #Add them in name zone name_zone.add(cost_wid) name_zone.add(star_wid) #Create an Image Zone image_zone=Button(self.card_win, command=self.choosePhoto) if hasattr(self,"photofile") and self.photofile : print ("Image: ",self.photofile) try : pilImage=Image.open(self.photofile) img=PhotoImage(pilImage,master=image_zone) except : decomp=self.photofile.split('/') for i in range(1,6) : try : fname="/".join(decomp[-i:]) print ("try to open",fname) pilImage = Image.open(fname) img=PhotoImage(pilImage,master=image_zone) self.photofile=fname break except : self.photofile=None if self.photofile : w, h = img.width(), img.height() print('wh',w,h) if h>400 : print("reduction") img=PhotoImage(pilImage.resize((w//2,h//2), Image.ANTIALIAS),master=image_zone) image_zone=Button(self.card_win,image=img, command=self.choosePhoto) image_zone.image=img #image_zone.configure(image=image_zone.image,width=50,height=50,compound=RIGHT) #image_zone.pack() #print "IMAGE CHANGED" else : from os import path fname=self.name.replace(" ","_") if path.isfile("Cards/"+fname+".png") : image_zone.config(text='image can be taken from\n'+"Cards/"+fname+".png",background='white',anchor=CENTER) else : image_zone.config(text='clic to choose image',background='white',anchor=CENTER) #image_zone.pack() # POWER ZONE power_zone=PanedWindow(self.card_win, orient=VERTICAL) #fenetre=self.card_win.master def removePowerCreator(px) : def removePower(*args) : #print 'avant',list_pow self.bonus.remove(px) #print 'apres',list_pow #self.card_win.pack_forget() self.refreshWidget() return removePower for p in self.bonus : powline = PanedWindow(self.card_win, orient=HORIZONTAL) pow_wid=p.initWidget(powline) powline.add(pow_wid) removepow=Button(powline, text="X", command=removePowerCreator(p), anchor=E) removepow.pack() powline.add(removepow) power_zone.add(powline) def addPower(*args) : if addBonus.get()!= "add bonus": name=addBonus.get() else: name=add_cost_alteration.get() print ("added :",name) import CardPowers self.bonus+=[eval('CardPowers.'+name+'()')] self.bonus[-1].parent=self.bonus self.bonus[-1].card=self #self.card_win.pack_forget() self.refreshWidget() #Add bonus Option menu addBonus = StringVar(power_zone) addBonus.set("add bonus") # default value if not self.pv: addBonus_wid = Spell.getSpellMenu(power_zone, addBonus) else: addBonus_wid = getBonusMenu(power_zone, addBonus) addBonus.trace('w', addPower) if self.pv>0 or len(self.bonus)==0 or all([b.is_cost_alterator for b in self.bonus]): addBonus_wid.pack() #Add this to power zone power_zone.add(addBonus_wid) #Create save zone save_zone = PanedWindow(self.card_win, orient=HORIZONTAL) if self.monster_type != "all" and not(self.name in Card.blocked_creature) : save_wid = Button(save_zone, text="Save", command=self.postAndSave) elif self.monster_type != "all" : save_wid = Button(save_zone, text="creature in campaign", command=None) else: save_wid = Button(save_zone, text="nead type", command=None) save_wid.pack() #Create the open button save_zone.pack() if Card.monster_list.keys(): self.opening = StringVar(save_zone) self.opening.set("Open") choice = [na for na in Card.monster_list.keys() if na not in Card.blocked_creature] choice.sort() #print all_monsters.keys() open_wid = OptionMenu(save_zone, self.opening,*choice) self.opening.trace('w', self.Open) open_wid.pack() save_zone.add(open_wid) if Card.monster_list.keys(): self.delete = StringVar(save_zone) self.delete.set("Delete") choice = [na for na in Card.monster_list.keys() if na not in Card.blocked_creature] choice.sort() delete_wid = OptionMenu(save_zone, self.delete,*choice) self.delete.trace('w', self.clicDelete) delete_wid.pack() save_zone.add(delete_wid) #Create the type button self.category = StringVar(save_zone) self.category.set(self.monster_type) choice = [file2name(t,"_monsters.sav") for t in glob.glob("CardFiles/*_monsters.sav")] if "recup" in choice: choice.remove("recup") #print all_monsters.keys() category_wid = OptionMenu(save_zone, self.category,*choice) self.category.trace('w', self.setFile) category_wid.pack() #Add it to save zone save_zone.add(save_wid) save_zone.add(category_wid) #Create a new Strength zone for att and pv strength_zone=PanedWindow(self.card_win, orient=HORIZONTAL) att=StringVar() att.set(str(self.att)) pv=StringVar() ; pv.set(str(self.pv)) def modifiedAttPv(*args) : print ("modifiedAttPv") self.pv=int(pv.get()) if self.pv<1 and self.is_spell==False : if len(self.bonus)==0 : self.is_spell=True self.refreshWidget() else : self.pv=1 self.refreshWidget() if self.pv>0 and self.is_spell==True : if len(self.bonus)==0 : self.is_spell=False self.refreshWidget() else : self.pv=0 self.refreshWidget() self.att=int(att.get()) self.getCost() att_wid = Spinbox(strength_zone, from_=0, to=1000,textvariable=att,command=modifiedAttPv) att_wid.pack() strength_zone.add(att_wid) strength_zone.add(Label(strength_zone, text=' ', background='white', anchor=CENTER)) pv_wid = Spinbox(strength_zone, from_=0, to=1000,textvariable=pv,command=modifiedAttPv) pv_wid.pack() strength_zone.add(pv_wid) #Put it all in window self.card_win.add(name_zone) self.card_win.add(image_zone) self.card_win.add(power_zone) self.card_win.add(strength_zone) self.card_win.add(save_zone) self.card_win.pack()
class OOP(): def __init__(self): # Create instance self.win = tk.Tk() # Add a title self.win.title("Python GUI") # Disable resizing the window self.win.resizable(0,0) # Create a Queue self.guiQueue = Queue() self.createWidgets() # populate Tab 2 Entries self.defaultFileEntries() # Start TCP/IP server in its own thread svrT = Thread(target=startServer, daemon=True) svrT.start() def defaultFileEntries(self): # populate Entry before making it read-only #self.fileEntry.config(state='readonly') self.fileEntry.delete(0, tk.END) #self.fileEntry.insert(0, fDir) self.fileEntry.insert(0, 'Z:\\') # bogus path # if len(fDir) > self.entryLen: # self.fileEntry.config(width=len(fDir) + 3) self.fileEntry.config(state='readonly') self.netwEntry.delete(0, tk.END) #self.netwEntry.insert(0, netDir) self.netwEntry.insert(0, 'Z:\\Backup') # bogus path # if len(netDir) > self.entryLen: # self.netwEntry.config(width=len(netDir) + 3) # Button callback def clickMe(self): self.action.configure(text='Hello ' + self.name.get()) # # Non-threaded code with sleep freezes the GUI # for idx in range(10): # sleep(5) # self.scr.insert(tk.INSERT, str(idx) + '\n') # # Threaded method does not freeze our GUI # self.createThread() # Passing in the current class instance (self) print(self) bq.writeToScrol(self) sleep(2) htmlData = url.getHtml() print(htmlData) self.scr.insert(tk.INSERT, htmlData) # Spinbox callback def _spin(self): value = self.spin.get() #print(value) self.scr.insert(tk.INSERT, value + '\n') # Checkbox callback def checkCallback(self, *ignoredArgs): # only enable one checkbutton if self.chVarUn.get(): self.check3.configure(state='disabled') else: self.check3.configure(state='normal') if self.chVarEn.get(): self.check2.configure(state='disabled') else: self.check2.configure(state='normal') # Radiobutton callback function def radCall(self): radSel=self.radVar.get() if radSel == 0: self.monty2.configure(text='Blue') elif radSel == 1: self.monty2.configure(text='Gold') elif radSel == 2: self.monty2.configure(text='Red') # Exit GUI cleanly def _quit(self): self.win.quit() self.win.destroy() exit() def methodInAThread(self): print('Hi, how are you?') # for idx in range(10): # sleep(5) # self.scr.insert(tk.INSERT, str(idx) + '\n') # def methodInAThread(self, numOfLoops=10): # for idx in range(numOfLoops): # sleep(1) # self.scr.insert(tk.INSERT, str(idx) + '\n') # sleep(1) # print('methodInAThread():', self.runT.isAlive()) # Running methods in Threads def createThread(self, num): self.runT = Thread(target=self.methodInAThread, args=[num]) self.runT.setDaemon(True) self.runT.start() print(self.runT) print('createThread():', self.runT.isAlive()) # textBoxes are the Consumers of Queue data writeT = Thread(target=self.useQueues, daemon=True) writeT.start() # Create Queue instance def useQueues(self): # guiQueue = Queue() # print(guiQueue) # for idx in range(10): # guiQueue.put('Message from a queue: ' + str(idx)) # while True: # print(guiQueue.get()) # Now using a class member Queue while True: qItem = self.guiQueue.get() print(qItem) self.scr.insert(tk.INSERT, qItem + '\n') ##################################################################################### def createWidgets(self): # Tab Control introduced here -------------------------------------- tabControl = ttk.Notebook(self.win) # Create Tab Control tab1 = ttk.Frame(tabControl) # Create a tab tabControl.add(tab1, text='Tab 1') # Add the tab tab2 = ttk.Frame(tabControl) # Add a second tab tabControl.add(tab2, text='Tab 2') # Make second tab visible tabControl.pack(expand=1, fill="both") # Pack to make visible # ~ Tab Control introduced here ----------------------------------------- # We are creating a container frame to hold all other widgets self.monty = ttk.LabelFrame(tab1, text=' Monty Python ') self.monty.grid(column=0, row=0, padx=8, pady=4) # Changing our Label ttk.Label(self.monty, text="Enter a name:").grid(column=0, row=0, sticky='W') # Adding a Textbox Entry widget self.name = tk.StringVar() nameEntered = ttk.Entry(self.monty, width=24, textvariable=self.name) nameEntered.grid(column=0, row=1, sticky='W') nameEntered.delete(0, tk.END) nameEntered.insert(0, '< default name >') # Adding a Button self.action = ttk.Button(self.monty, text="Click Me!", command=self.clickMe) self.action.grid(column=2, row=1) ttk.Label(self.monty, text="Choose a number:").grid(column=1, row=0) number = tk.StringVar() numberChosen = ttk.Combobox(self.monty, width=14, textvariable=number) numberChosen['values'] = (1, 2, 4, 42, 100) numberChosen.grid(column=1, row=1) numberChosen.current(0) # Adding a Spinbox widget using a set of values self.spin = Spinbox(self.monty, values=(1, 2, 4, 42, 100), width=5, bd=8, command=self._spin) self.spin.grid(column=0, row=2, sticky='W') # Using a scrolled Text control scrolW = 40; scrolH = 10 self.scr = scrolledtext.ScrolledText(self.monty, width=scrolW, height=scrolH, wrap=tk.WORD) self.scr.grid(column=0, row=3, sticky='WE', columnspan=3) # Tab Control 2 refactoring --------------------------------------------------- # We are creating a container frame to hold all other widgets -- Tab2 self.monty2 = ttk.LabelFrame(tab2, text=' The Snake ') self.monty2.grid(column=0, row=0, padx=8, pady=4) # Creating three checkbuttons chVarDis = tk.IntVar() check1 = tk.Checkbutton(self.monty2, text="Disabled", variable=chVarDis, state='disabled') check1.select() check1.grid(column=0, row=0, sticky=tk.W) self.chVarUn = tk.IntVar() self.check2 = tk.Checkbutton(self.monty2, text="UnChecked", variable=self.chVarUn) self.check2.deselect() self.check2.grid(column=1, row=0, sticky=tk.W ) self.chVarEn = tk.IntVar() self.check3 = tk.Checkbutton(self.monty2, text="Toggle", variable=self.chVarEn) self.check3.deselect() self.check3.grid(column=2, row=0, sticky=tk.W) # trace the state of the two checkbuttons self.chVarUn.trace('w', lambda unused0, unused1, unused2 : self.checkCallback()) self.chVarEn.trace('w', lambda unused0, unused1, unused2 : self.checkCallback()) # ~ Tab Control 2 refactoring ----------------------------------------- # Radiobutton list colors = ["Blue", "Gold", "Red"] self.radVar = tk.IntVar() # Selecting a non-existing index value for radVar self.radVar.set(99) # Creating all three Radiobutton widgets within one loop for col in range(3): curRad = 'rad' + str(col) curRad = tk.Radiobutton(self.monty2, text=colors[col], variable=self.radVar, value=col, command=self.radCall) curRad.grid(column=col, row=6, sticky=tk.W, columnspan=3) # And now adding tooltips tt.createToolTip(curRad, 'This is a Radiobutton control.') # Create a container to hold labels labelsFrame = ttk.LabelFrame(self.monty2, text=' Labels in a Frame ') labelsFrame.grid(column=0, row=7) # Place labels into the container element - vertically ttk.Label(labelsFrame, text="Label1").grid(column=0, row=0) ttk.Label(labelsFrame, text="Label2").grid(column=0, row=1) # Add some space around each label for child in labelsFrame.winfo_children(): child.grid_configure(padx=8) # Create Manage Files Frame ------------------------------------------------ mngFilesFrame = ttk.LabelFrame(tab2, text=' Manage Files: ') mngFilesFrame.grid(column=0, row=1, sticky='WE', padx=10, pady=5) # Button Callback def getFileName(): print('hello from getFileName') fDir = path.dirname(__file__) fName = fd.askopenfilename(parent=self.win, initialdir=fDir) print(fName) self.fileEntry.config(state='enabled') self.fileEntry.delete(0, tk.END) self.fileEntry.insert(0, fName) if len(fName) > self.entryLen: self.fileEntry.config(width=len(fName) + 3) # Add Widgets to Manage Files Frame lb = ttk.Button(mngFilesFrame, text="Browse to File...", command=getFileName) lb.grid(column=0, row=0, sticky=tk.W) #----------------------------------------------------- file = tk.StringVar() self.entryLen = scrolW - 4 self.fileEntry = ttk.Entry(mngFilesFrame, width=self.entryLen, textvariable=file) self.fileEntry.grid(column=1, row=0, sticky=tk.W) #----------------------------------------------------- logDir = tk.StringVar() self.netwEntry = ttk.Entry(mngFilesFrame, width=self.entryLen, textvariable=logDir) self.netwEntry.grid(column=1, row=1, sticky=tk.W) def copyFile(): import shutil src = self.fileEntry.get() file = src.split('/')[-1] dst = self.netwEntry.get() + '\\'+ file try: shutil.copy(src, dst) mBox.showinfo('Copy File to Network', 'Succes: File copied.') except FileNotFoundError as err: mBox.showerror('Copy File to Network', '*** Failed to copy file! ***\n\n' + str(err)) except Exception as ex: mBox.showerror('Copy File to Network', '*** Failed to copy file! ***\n\n' + str(ex)) cb = ttk.Button(mngFilesFrame, text="Copy File To : ", command=copyFile) cb.grid(column=0, row=1, sticky=tk.E) # Add some space around each label for child in mngFilesFrame.winfo_children(): child.grid_configure(padx=6, pady=6) # Creating a Menu Bar ========================================================== menuBar = Menu(tab1) self.win.config(menu=menuBar) # Add menu items fileMenu = Menu(menuBar, tearoff=0) fileMenu.add_command(label="New") fileMenu.add_separator() fileMenu.add_command(label="Exit", command=self._quit) menuBar.add_cascade(label="File", menu=fileMenu) # Add another Menu to the Menu Bar and an item helpMenu = Menu(menuBar, tearoff=0) helpMenu.add_command(label="About") menuBar.add_cascade(label="Help", menu=helpMenu) # Change the main windows icon self.win.iconbitmap(r'C:\Python34\DLLs\pyc.ico') # Using tkinter Variable Classes strData = tk.StringVar() strData.set('Hello StringVar') # It is not necessary to create a tk.StringVar() strData = tk.StringVar() strData = self.spin.get() # Place cursor into name Entry # nameEntered.focus() # Set focus to Tab 2 tabControl.select(1) # Add a Tooltip to the Spinbox tt.createToolTip(self.spin, 'This is a Spin control.') # Add Tooltips to more widgets tt.createToolTip(nameEntered, 'This is an Entry control.') tt.createToolTip(self.action, 'This is a Button control.') tt.createToolTip(self.scr, 'This is a ScrolledText control.')
# 我们调用创建工具提示的函数,然后将引用传递给当鼠标悬停在小部件上时,我们希望显示小部件和文本。 createToolTip(scr, 'This is a ScrolledText widget.') # Spinbox callback def _spin(): value = spin.get() print(value) scr.insert(tk.INSERT, value + '\n') # 设置不同的relief的属性来改变spinbox的形状,tk.SUNKEN tk.RAISED tk.FLAT tk.GROOVE tk.RIDGE spin = Spinbox(monty, from_=0, to=10, width=5, bd=8, relief=tk.RIDGE, command=_spin) spin.grid(column=0, row=2) # 注意与第一个spinbox对比 spin = Spinbox(monty, values=(0, 50, 100), width=5, bd=20, relief=tk.GROOVE, command=_spin) spin.grid(column=1, row=2) createToolTip(spin, 'This is a Spin control.')
root.title("Password Generator") title_label = Label( root, width=23, height=2, text="Password Generator", font=("Helvetica 16 bold"), bg="#bfbfbf", ) title_label.grid(row=0, column=0, columnspan=3, pady=[0, 30]) length_label = Label(root, text="Length:", font={"Helvetica 25"}) length_label.grid(row=1, column=0, sticky="e") length_input = Spinbox(root, width=3, from_=1, to=15, font=("Helvetica", 20)) length_input.insert(1, 0) length_input.grid(row=1, column=1) generate_button = Button(root, text="Generate", font=("Helvetica 12"), command=generate_password) generate_button.grid(row=1, column=2, sticky="w") password_display = Entry(root, width=15, font=("Helvetica 20"), bd=0, bg="systembuttonface", justify="center")
class DrumMachine: def __init__(self, root): self.root = root self.root.title(PROGRAM_NAME) self.all_patterns = [None] * MAX_NUMBER_OF_PATTERNS self.beats_per_minute = INITIAL_BEATS_PER_MINUTE self.current_pattern_index = 0 self.drum_load_entry_widget = [None] * MAX_NUMBER_OF_DRUM_SAMPLES self.init_all_patterns() self.init_gui() # # getters and setters begins # def get_current_pattern_dict(self): return self.all_patterns[self.current_pattern_index] def get_bpu(self): return self.get_current_pattern_dict()['bpu'] def set_bpu(self): self.get_current_pattern_dict()['bpu'] = int(self.bpu_widget.get()) def get_number_of_units(self): return self.get_current_pattern_dict()['number_of_units'] def set_number_of_units(self): self.get_current_pattern_dict( )['number_of_units'] = int(self.number_of_units_widget.get()) def get_list_of_drum_files(self): return self.get_current_pattern_dict()['list_of_drum_files'] def get_drum_file_path(self, drum_index): return self.get_list_of_drum_files()[drum_index] def set_drum_file_path(self, drum_index, file_path): self.get_list_of_drum_files()[drum_index] = file_path def get_is_button_clicked_list(self): return self.get_current_pattern_dict()['is_button_clicked_list'] def set_is_button_clicked_list(self, num_of_rows, num_of_columns): self.get_current_pattern_dict()['is_button_clicked_list'] = [ [False] * num_of_columns for x in range(num_of_rows)] def init_all_patterns(self): self.all_patterns = [ { 'list_of_drum_files': [None] * MAX_NUMBER_OF_DRUM_SAMPLES, 'number_of_units': INITIAL_NUMBER_OF_UNITS, 'bpu': INITIAL_BPU, 'is_button_clicked_list': self.init_is_button_clicked_list( MAX_NUMBER_OF_DRUM_SAMPLES, INITIAL_NUMBER_OF_UNITS * INITIAL_BPU ) } for k in range(MAX_NUMBER_OF_PATTERNS)] def on_pattern_changed(self): pass def on_number_of_units_changed(self): self.set_number_of_units() self.set_is_button_clicked_list(MAX_NUMBER_OF_DRUM_SAMPLES, self.find_number_of_columns()) self.create_right_button_matrix() def on_bpu_changed(self): self.set_bpu() self.set_is_button_clicked_list(MAX_NUMBER_OF_DRUM_SAMPLES, self.find_number_of_columns()) self.create_right_button_matrix() def on_open_file_button_clicked(self, drum_index): pass def on_play_button_clicked(self): pass def on_stop_button_clicked(self): pass def on_loop_button_toggled(self): pass def on_beats_per_minute_changed(self): pass def init_is_button_clicked_list(self, num_of_rows, num_of_columns): return [[False] * num_of_columns for x in range(num_of_rows)] def get_button_value(self, row, col): return self.all_patterns[self.current_pattern_index][ 'is_button_clicked_list'][row][col] def find_number_of_columns(self): return int(self.number_of_units_widget.get()) * int(self.bpu_widget.get()) def process_button_clicked(self, row, col): self.set_button_value(row, col, not self.get_button_value(row, col)) self.display_button_color(row, col) def set_button_value(self, row, col, bool_value): self.all_patterns[self.current_pattern_index][ 'is_button_clicked_list'][row][col] = bool_value def on_button_clicked(self, row, col): def event_handler(): self.process_button_clicked(row, col) return event_handler def display_all_button_colors(self): number_of_columns = self.find_number_of_columns() for r in range(MAX_NUMBER_OF_DRUM_SAMPLES): for c in range(number_of_columns): self.display_button_color(r, c) def display_button_color(self, row, col): bpu = int(self.bpu_widget.get()) original_color = COLOR_1 if ((col//bpu) % 2) else COLOR_2 button_color = BUTTON_CLICKED_COLOR if self.get_button_value( row, col) else original_color self.buttons[row][col].config(background=button_color) def create_play_bar(self): playbar_frame = Frame(self.root, height=15) start_row = MAX_NUMBER_OF_DRUM_SAMPLES + 10 playbar_frame.grid(row=start_row, columnspan=13, sticky=W + E, padx=15, pady=10) self.play_icon = PhotoImage(file="images/play.gif") self.play_button = Button( playbar_frame, text='Play', image=self.play_icon, compound='left', command=self.on_play_button_clicked) self.play_button.grid(row=start_row, column=1, padx=2) Button(playbar_frame, text='Stop', command=self.on_stop_button_clicked).grid( row=start_row, column=3, padx=2) self.loopbutton = Checkbutton( playbar_frame, text='Loop', command=self.on_loop_button_toggled) self.loopbutton.grid(row=start_row, column=16, padx=5) Label(playbar_frame, text='Beats Per Minute').grid( row=start_row, column=25) self.beats_per_minute_widget = Spinbox(playbar_frame, from_=MIN_BEATS_PER_MINUTE, to=MAX_BEATS_PER_MINUTE, width=5, increment=5.0, command=self.on_beats_per_minute_changed) self.beats_per_minute_widget.grid(row=start_row, column=30) self.beats_per_minute_widget.delete(0,"end") self.beats_per_minute_widget.insert(0,INITIAL_BEATS_PER_MINUTE) photo = PhotoImage(file='images/signature.gif') label = Label(playbar_frame, image=photo) label.image = photo label.grid(row=start_row, column=50, padx=1, sticky='w') def create_right_button_matrix(self): right_frame = Frame(self.root) right_frame.grid(row=10, column=6, sticky=W + E + N + S, padx=15, pady=4) self.buttons = [[None for x in range( self.find_number_of_columns())] for x in range(MAX_NUMBER_OF_DRUM_SAMPLES)] for row in range(MAX_NUMBER_OF_DRUM_SAMPLES): for col in range(self.find_number_of_columns()): self.buttons[row][col] = Button( right_frame, command=self.on_button_clicked(row, col)) self.buttons[row][col].grid(row=row, column=col) self.display_button_color(row, col) def create_left_drum_loader(self): left_frame = Frame(self.root) left_frame.grid(row=10, column=0, columnspan=6, sticky=W + E + N + S) open_file_icon = PhotoImage(file='images/openfile.gif') for i in range(MAX_NUMBER_OF_DRUM_SAMPLES): open_file_button = Button(left_frame, image=open_file_icon, command=self.on_open_file_button_clicked(i)) open_file_button.image = open_file_icon open_file_button.grid(row=i, column=0, padx=5, pady=4) self.drum_load_entry_widget[i] = Entry(left_frame) self.drum_load_entry_widget[i].grid( row=i, column=4, padx=7, pady=4) def create_top_bar(self): topbar_frame = Frame(self.root, height=25) topbar_frame.grid(row=0, columnspan=12, rowspan=10, padx=5, pady=5) Label(topbar_frame, text='Pattern Number:').grid(row=0, column=1) self.pattern_index_widget = Spinbox(topbar_frame, from_=0, to=MAX_NUMBER_OF_PATTERNS - 1, width=5, command=self.on_pattern_changed) self.pattern_index_widget.grid(row=0, column=2) self.current_pattern_name_widget = Entry(topbar_frame) self.current_pattern_name_widget.grid(row=0, column=3, padx=7, pady=2) Label(topbar_frame, text='Number of Units:').grid(row=0, column=4) self.number_of_units_widget = Spinbox(topbar_frame, from_=1, to=MAX_NUMBER_OF_UNITS, width=5, command=self.on_number_of_units_changed) self.number_of_units_widget.delete(0,"end") self.number_of_units_widget.insert(0,INITIAL_NUMBER_OF_UNITS) self.number_of_units_widget.grid(row=0, column=5) Label(topbar_frame, text='BPUs:').grid(row=0, column=6) self.bpu_widget = Spinbox(topbar_frame, from_=1, to=MAX_BPU, width=5, command=self.on_bpu_changed) self.bpu_widget.grid(row=0, column=7) self.bpu_widget.delete(0,"end") self.bpu_widget.insert(0,INITIAL_BPU) def create_top_menu(self): self.menu_bar = Menu(self.root) self.file_menu = Menu(self.menu_bar, tearoff=0) self.file_menu.add_command(label="Load Project") self.file_menu.add_command(label="Save Project") self.file_menu.add_separator() self.file_menu.add_command(label="Exit") self.menu_bar.add_cascade(label="File", menu=self.file_menu) self.about_menu = Menu(self.menu_bar, tearoff=0) self.about_menu.add_command(label="About") self.menu_bar.add_cascade(label="About", menu=self.about_menu) self.root.config(menu=self.menu_bar) def init_gui(self): self.create_top_menu() self.create_top_bar() self.create_left_drum_loader() self.create_right_button_matrix() self.create_play_bar()
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("") #self.style = Style() #self.style.theme_use("clam") #self.pack(fill=BOTH, expand = 1) self.quitbutton = Button(self, text="Quit", command= lambda: self.quit()) self.quitbutton.grid(row=3, column=1, pady=4) self.labelErrorPointer = Label(self, text="◀") self.labellist = [] self.entrylist = [] self.verifylist = [] self.misclist = [] self.optionCreate = "Create" self.optionUpcoming = "Upcoming" self.optionPast = "Past" self.prevmode = self.optionCreate self.curmode = self.optionCreate self.optionvar = tkinter.StringVar(self) self.optionvar.trace("w",self.permaloop) self.optionvar.set(self.optionCreate) self.option = OptionMenu(self, self.optionvar, self.optionCreate, self.optionUpcoming, self.optionPast) self.optionpostmodevar = tkinter.StringVar(self) self.optionpostmodevar.trace("w",self.permaloop) self.optionpostmodevar.set('url') self.optionpostmode = OptionMenu(self, self.optionpostmodevar, 'url', 'text') self.labelText = Label(self, text='Selftext:') self.entryText = Text(self) self.labelURL = Label(self, text='URL:') self.entryURL = Entry(self) self.entryURL.configure(width=60) self.sql = sqlite3.connect('sql.db') print('Loaded SQL Database') self.cur = self.sql.cursor() self.cur.execute('CREATE TABLE IF NOT EXISTS upcoming(ID TEXT, SUBREDDIT TEXT, TIME INT, TITLE TEXT, URL TEXT, BODY TEXT)') self.cur.execute('CREATE TABLE IF NOT EXISTS past(ID TEXT, SUBREDDIT TEXT, TIME INT, TITLE TEXT, URL TEXT, BODY TEXT, POSTLINK TEXT)') self.cur.execute('CREATE TABLE IF NOT EXISTS internal(NAME TEXT, ID INT)') print('Loaded Completed table') self.cur.execute('SELECT * FROM internal') f = self.cur.fetchone() if not f: print('Database is new. Adding ID counter') self.cur.execute('INSERT INTO internal VALUES(?, ?)', ['counter', 1]) self.idcounter = 1 else: self.idcounter = f[1] print('Current ID counter: ' + str(self.idcounter)) self.sql.commit() sw = self.parent.winfo_screenwidth() sh = self.parent.winfo_screenheight() w=853 h=480 x = (sw - w) / 2 y = (sh - h) / 2 self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y-50)) self.login() def login(self): try: self.quitbutton.grid_forget() self.quitbutton.grid(row=9000, column=0, columnspan=20) self.option.grid(row=1,column=0,columnspan=80,pady=8) self.updategui(fullclean=True) except praw.errors.InvalidUserPass: pass print('Invalid username or password') self.entryPassword.delete(0,200) self.labelErrorPointer.grid(row=1, column=2) def permaloop(self, *args): self.curmode = self.optionvar.get() print('Was: ' + self.prevmode + ' | Now: ' + self.curmode) if self.curmode != self.prevmode: self.prevmode = self.curmode self.updategui(fullclean=True) else: self.updategui(False) def getTime(self, bool): timeNow = datetime.datetime.now(datetime.timezone.utc) timeUnix = timeNow.timestamp() if bool is False: return timeNow else: return timeUnix def addentrytobase(self, subreddit, title, url="", body="", mode="", ptime=""): curtime = round(self.getTime(True)) try: t = self.entryMo.get() + ' ' + self.entryDa.get() + ' ' + self.entryYr.get() + ' ' + self.entryHH.get() + ':' + self.entryMM.get() plandate = datetime.datetime.strptime(t, "%B %d %Y %H:%M") plandate = plandate.timestamp() except ValueError: print('Invalid Day') return False if mode == 'url': url = self.entryURL.get() body = "" if 'http://' not in url and 'https://' not in url: print('Please enter a proper URL') return False if mode == 'text': body = self.entryText.get("1.0", "end") url = "" if plandate < curtime: print('Please enter a time in the future') return False if not all(char in string.ascii_letters+string.digits+'_-' for char in subreddit): print('Subreddit contains invalid characters') return False if len(subreddit) == 0: print('You must enter a subreddit') return False if len(title) == 0: print('You must enter a title') return False if len(title) > 300: print('Title is too long. ' + str(len(title)) + '/300 char max') return False if len(body) > 15000: print('Body is too long. ' + str(len(body)) + '/15,000 char max') print('Timestamp:', plandate) self.cur.execute('INSERT INTO upcoming VALUES(?, ?, ?, ?, ?, ?)', [self.idcounter, subreddit, int(plandate), title, url, body]) self.idcounter += 1 self.cur.execute('UPDATE internal SET ID=? WHERE NAME=?', [self.idcounter, 'counter']) self.sql.commit() print('\nPost Saved!') print(self.idcounter, subreddit, self.timestamptoday(int(plandate))) print(title) print(url, body) print() self.entryText.delete("1.0", "end") self.entryURL.delete(0, 'end') self.entryTitle.delete(0, 'end') #self.updategui(halfclean=True) def timestamptoday(self, timestamp): d = datetime.datetime.fromtimestamp(timestamp) info = datetime.datetime.strftime(d, "%b %d %H:%M") return info def dropentryfrombase(self, ID): if '-' not in ID: try: ID = int(ID) l = [ID] except ValueError: print('You must enter a number') return else: if ID.count('-') == 1: try: ID = ID.replace(' ', '') ID = ID.split('-') ID[0] = int(ID[0]) ID[1] = int(ID[1]) if ID[1] > ID[0]: l = list(range(ID[0], ID[1]+1)) else: return except ValueError: return for item in l: item = str(item) print('Dropping Item ' + item + ' from Upcoming') self.cur.execute('DELETE FROM upcoming WHERE ID=?', [item]) self.sql.commit() self.updategui(fullclean=True) def printbasetofile(self, db): filea = open(db + '.txt', 'w') if db == 'past': self.cur.execute('SELECT * FROM past') if db == 'upcoming': self.cur.execute('SELECT * FROM upcoming') f = self.cur.fetchall() print('Printed ' + db + ' unimpeded to file') for item in f: i = list(item) i[2] = self.timestamptoday(i[2]) i.remove('') print(str(i)[1:-1], file=filea) filea.close() def updategui(self, halfclean=False, fullclean=False): if self.curmode == self.optionCreate: try: print(self.optionpostmodevar.get()) if self.optionpostmodevar.get() == 'url': self.entryText.delete("1.0", 'end') self.labelText.grid_forget() self.entryText.grid_forget() self.labelURL.grid(row=8, column=0, columnspan=30) self.entryURL.grid(row=9, column=0, columnspan=12, pady=10) if self.optionpostmodevar.get() == 'text': self.entryURL.delete(0, 'end') self.labelURL.grid_forget() self.entryURL.grid_forget() self.labelText.grid(row=8, column=0, columnspan=30) self.entryText.configure(width=40, height=8) self.entryText.grid(row=9, column=0, columnspan=12) except AttributeError: pass if fullclean is True: print('Cleaning GUI') for item in self.labellist: item.grid_forget() for item in self.entrylist: item.grid_forget() for item in self.verifylist: item.grid_forget() for item in self.misclist: item.grid_forget() self.labellist = [] self.entrylist = [] self.verifylist = [] self.misclist = [] if self.curmode == self.optionCreate: self.newrowindex = 6 self.labelSubreddit = Label(self, text="Subreddit: /r/") self.labelTitle = Label(self, text="Post title: ") self.entrySubreddit = Entry(self) self.entryTitle = Entry(self) self.labelHH = Label(self, text="Schedule time (Local timezone):") nowlist = datetime.datetime.strftime(datetime.datetime.now(), "%B %d %Y %H %M").split() self.entryMo = Spinbox(self, width=9, values=('January', 'February', 'March', 'April', 'May', 'June', 'July', \ 'August', 'September', 'October', 'November', 'December')) self.entryMo.delete(0,'end') self.entryMo.insert(0, nowlist[0]) self.entryDa = Spinbox(self, width=2, from_=1, to=31) self.entryDa.delete(0,'end') self.entryDa.insert(0, nowlist[1]) self.entryYr = Spinbox(self, width=4, from_=2014, to=2500) self.entryYr.delete(0,'end') self.entryYr.insert(0, nowlist[2]) self.entryHH = Spinbox(self, from_=0, to=23, width=2) self.entryHH.delete(0,'end') self.entryHH.insert(0, nowlist[3]) self.entryMM = Spinbox(self, from_=0, to=59, width=2) self.entryMM.delete(0,'end') self.entryMM.insert(0, nowlist[4]) self.buttonAddentry = Button(self, text='Save', command=lambda: self.addentrytobase(self.entrySubreddit.get(), self.entryTitle.get(),\ mode=self.optionpostmodevar.get())) self.misclist.append(self.labelSubreddit) self.misclist.append(self.entrySubreddit) self.misclist.append(self.labelHH) self.misclist.append(self.entryHH) self.misclist.append(self.entryMM) self.misclist.append(self.entryMo) self.misclist.append(self.entryDa) self.misclist.append(self.entryYr) self.misclist.append(self.labelTitle) self.misclist.append(self.entryTitle) self.misclist.append(self.buttonAddentry) self.misclist.append(self.optionpostmode) self.misclist.append(self.labelText) self.misclist.append(self.entryText) self.misclist.append(self.labelURL) self.misclist.append(self.entryURL) self.labelSubreddit.grid(row=2, column=0, sticky="e") self.labelTitle.grid(row=3, column=0, sticky="e") self.entrySubreddit.grid(row=2, column=1, columnspan=3, sticky="w") self.entryTitle.grid(row=3, column=1, columnspan=3, sticky="w") self.entryMo.grid(row=4, column=1,sticky="e") self.entryDa.grid(row=4, column=2) self.entryYr.grid(row=4, column=3) self.labelHH.grid(row=4, column=0, sticky="se", pady=5) self.entryHH.grid(row=5, column=1, sticky="e") self.entryMM.grid(row=5, column=2, sticky="w") self.optionpostmode.grid(row=6, column=0, columnspan=20, pady=10) self.buttonAddentry.grid(row=200, column=0, columnspan=20) if self.curmode == self.optionUpcoming: self.cur.execute('SELECT * FROM upcoming') dobutton = True if self.curmode == self.optionPast: self.cur.execute('SELECT * FROM past') dobutton = False if self.curmode == self.optionPast or self.curmode == self.optionUpcoming: self.listboxId = Listbox(self) self.listboxId.configure(width=118, height=20, font=("Courier 8")) self.misclist.append(self.listboxId) self.listboxScroller = Scrollbar(self, orient='horizontal', command=self.listboxId.xview) self.listboxScroller.grid(row=4, column=0, columnspan=900) self.listboxId.grid(row=3, column=0, columnspan=10) self.listboxId.configure(xscrollcommand=self.listboxScroller.set) self.misclist.append(self.listboxScroller) self.buttonPrinter = Button(self, text="Print to .txt file") if self.curmode == self.optionPast: self.buttonPrinter.configure(command=lambda: self.printbasetofile('past')) if self.curmode == self.optionUpcoming: self.buttonPrinter.configure(command=lambda: self.printbasetofile('upcoming')) self.buttonPrinter.grid(row = 6, column=0, columnspan=90) self.misclist.append(self.buttonPrinter) if dobutton is True: self.entryDelete = Entry(self) self.buttonDelete = Button(self, text="Delete Item: ", command=lambda: self.dropentryfrombase(self.entryDelete.get())) self.buttonDelete.grid(row=5, column=0, sticky='e') self.entryDelete.grid(row=5, column=1, sticky='w') self.misclist.append(self.entryDelete) self.misclist.append(self.buttonDelete) fetched = self.cur.fetchall() for item in fetched: info = self.timestamptoday(item[2]) if item[4] == '': infx = item[5] if item[5] == '': infx = item[4] if self.curmode == self.optionPast: infy = '.' + item[6] else: infy = '' self.listboxId.insert('end', \ item[0] + '.'*(6 - len(item[0])) \ + item[1][:10] + '.'*(12 - len(item[1][:10])) \ + info + '.'*(15 - len(info[:14])) \ + item[3][:18] + '.'*(20 - len(item[3][:14])) \ + infx[:45] + '.'*(47-len(infx[:45])) \ + infy) def morerows(self, label, columnm, columnn, limit, *args): self.redditlabel = Label(self,text=label) self.redditlabel.grid(row=self.newrowindex,column=columnm, sticky="e") self.labellist.append(self.redditlabel) self.redditentry = Entry(self) self.redditentry.grid(row=self.newrowindex,column=columnn, columnspan=9) self.entrylist.append(self.redditentry) self.newrowindex += 1 if self.newrowindex >= limit: self.morerowbutton.grid_forget() print(self.newrowindex)
def createWidgets(self): # Tab Control introduced here -------------------------------------- tabControl = ttk.Notebook(self.win) # Create Tab Control tab1 = ttk.Frame(tabControl) # Create a tab tabControl.add(tab1, text='Tab 1') # Add the tab tab2 = ttk.Frame(tabControl) # Add a second tab tabControl.add(tab2, text='Tab 2') # Make second tab visible tabControl.pack(expand=1, fill="both") # Pack to make visible # ~ Tab Control introduced here ----------------------------------------- # We are creating a container frame to hold all other widgets self.monty = ttk.LabelFrame(tab1, text=' Mighty Python ') self.monty.grid(column=0, row=0, padx=8, pady=4) # Changing our Label ttk.Label(self.monty, text="Enter a name:").grid(column=0, row=0, sticky='W') # Adding a Textbox Entry widget self.name = tk.StringVar() nameEntered = ttk.Entry(self.monty, width=12, textvariable=self.name) nameEntered.grid(column=0, row=1, sticky='W') # Adding a Button self.action = ttk.Button(self.monty, text="Click Me!", command=self.clickMe) self.action.grid(column=2, row=1) ttk.Label(self.monty, text="Choose a number:").grid(column=1, row=0) number = tk.StringVar() numberChosen = ttk.Combobox(self.monty, width=12, textvariable=number) numberChosen['values'] = (1, 2, 4, 42, 100) numberChosen.grid(column=1, row=1) numberChosen.current(0) # Adding a Spinbox widget using a set of values self.spin = Spinbox(self.monty, values=(1, 2, 4, 42, 100), width=5, bd=8, command=self._spin) self.spin.grid(column=0, row=2) # Using a scrolled Text control scrolW = 30; scrolH = 3 self.scr = scrolledtext.ScrolledText(self.monty, width=scrolW, height=scrolH, wrap=tk.WORD) self.scr.grid(column=0, row=3, sticky='WE', columnspan=3) # TODO: ch11 new #------------------------------------------------------------------------- #------------------------------------------------------------------------- # Adding another Button self.action = ttk.Button(self.monty, text="Clear Text", command=self.clearScrol) self.action.grid(column=2, row=2) # Adding more Feature Buttons startRow = 4 for idx in range(12): if idx < 2: colIdx = idx col = colIdx else: col += 1 if not idx % 3: startRow += 1 col = 0 b = ttk.Button(self.monty, text="Feature " + str(idx+1)) b.grid(column=col, row=startRow) # Tab Control 3 ----------------------------------------- tab3 = ttk.Frame(tabControl) # Add a tab tabControl.add(tab3, text='Tab 3') # Make tab visible # We are creating a container frame to hold all other widgets -- Tab3 monty3 = ttk.LabelFrame(tab3, text=' New Features ') monty3.grid(column=0, row=0, padx=8, pady=4) # Adding more Feature Buttons startRow = 4 for idx in range(24): if idx < 2: colIdx = idx col = colIdx else: col += 1 if not idx % 3: startRow += 1 col = 0 b = ttk.Button(monty3, text="Feature " + str(idx+1)) b.grid(column=col, row=startRow) # Add some space around each label for child in monty3.winfo_children(): child.grid_configure(padx=8) #------------------------------------------------------------------------- # TODO: ch11 new end # Tab Control 2 refactoring ----------------------------------------- # We are creating a container frame to hold all other widgets -- Tab2 self.monty2 = ttk.LabelFrame(tab2, text=' Holy Grail ') self.monty2.grid(column=0, row=0, padx=8, pady=4) # Creating three checkbuttons chVarDis = tk.IntVar() check1 = tk.Checkbutton(self.monty2, text="Disabled", variable=chVarDis, state='disabled') check1.select() check1.grid(column=0, row=0, sticky=tk.W) self.chVarUn = tk.IntVar() self.check2 = tk.Checkbutton(self.monty2, text="UnChecked", variable=self.chVarUn) self.check2.deselect() self.check2.grid(column=1, row=0, sticky=tk.W ) self.chVarEn = tk.IntVar() self.check3 = tk.Checkbutton(self.monty2, text="Toggle", variable=self.chVarEn) self.check3.deselect() self.check3.grid(column=2, row=0, sticky=tk.W) # trace the state of the two checkbuttons self.chVarUn.trace('w', lambda unused0, unused1, unused2 : self.checkCallback()) self.chVarEn.trace('w', lambda unused0, unused1, unused2 : self.checkCallback()) # ~ Tab Control 2 refactoring ----------------------------------------- # Radiobutton list colors = ["Blue", "Gold", "Red"] self.radVar = tk.IntVar() # Selecting a non-existing index value for radVar self.radVar.set(99) # Creating all three Radiobutton widgets within one loop for col in range(3): curRad = 'rad' + str(col) curRad = tk.Radiobutton(self.monty2, text=colors[col], variable=self.radVar, value=col, command=self.radCall) curRad.grid(column=col, row=6, sticky=tk.W, columnspan=3) # And now adding tooltips tt.createToolTip(curRad, 'This is a Radiobutton control.') # Create a container to hold labels labelsFrame = ttk.LabelFrame(self.monty2, text=' Labels in a Frame ') labelsFrame.grid(column=0, row=7) # Place labels into the container element - vertically ttk.Label(labelsFrame, text="Label1").grid(column=0, row=0) ttk.Label(labelsFrame, text="Label2").grid(column=0, row=1) # Add some space around each label for child in labelsFrame.winfo_children(): child.grid_configure(padx=8) # Creating a Menu Bar menuBar = Menu(tab1) self.win.config(menu=menuBar) # Add menu items fileMenu = Menu(menuBar, tearoff=0) fileMenu.add_command(label="New") fileMenu.add_separator() fileMenu.add_command(label="Exit", command=self._quit) menuBar.add_cascade(label="File", menu=fileMenu) # Add another Menu to the Menu Bar and an item helpMenu = Menu(menuBar, tearoff=0) helpMenu.add_command(label="About") menuBar.add_cascade(label="Help", menu=helpMenu) # Change the main windows icon self.win.iconbitmap('pyc.ico') # Using tkinter Variable Classes strData = tk.StringVar() strData.set('Hello StringVar') print(strData.get()) # Default tkinter Variable Classes intData = tk.IntVar() print(intData.get()) print(tk.DoubleVar()) print(tk.BooleanVar()) # It is not necessary to create a tk.StringVar() strData = tk.StringVar() strData = self.spin.get() print("Hello " + strData) # Printing the Global works print(GLOBAL_CONST) # call method self.usingGlobal() # Place cursor into name Entry nameEntered.focus() # Add a Tooltip to the Spinbox tt.createToolTip(self.spin, 'This is a Spin control.') # Add Tooltips to more widgets tt.createToolTip(nameEntered, 'This is an Entry control.') tt.createToolTip(self.action, 'This is a Button control.') tt.createToolTip(self.scr, 'This is a ScrolledText control.')
def on_click(): file = filedialog.askopenfilename(filetypes=(("Text files", "*.txt"), ("all files", "*.*"))) f = open(file) names = f.read() names = names.splitlines() f.close() my_text.config(state='normal') my_text.delete(1.0, END) my_text.config(state='disabled') for name in names: my_text.config(state='normal') my_text.insert(END, name) my_text.insert(END, '\n') my_text.config(state='disabled') def on_gen(): space3 = Label(window, height=1, bg='coral') space3.grid(column=1, row=11) window.geometry('480x750') window.minsize(480, 750) window.maxsize(480, 750) show_output = scrolledtext.ScrolledText(window, width=55, height=10, font=('Arial Bold', 11), state='disabled') show_output.grid(column=1, row=12) show_output.config(state='normal') show_output.delete(1.0, END) show_output.config(state='disabled') show_output.config(state='normal') delay = time.get() t_end = t.time() + int(delay) while t.time() <= t_end: f_name = random.choice(names) l_name = random.choice(names) f_len = len(f_name) l_len = len(l_name) if f_len == 3 and l_len == 3: f_3 = f3(f_name) l_3 = l3(l_name) bro = f_3 + l_3 br = ''.join(bro) show_output.insert(END, br) show_output.insert(END, '\n') elif f_len == 3 and l_len > 3: f_3 = f3(f_name) l_4 = l4(l_name) bro = f_3 + l_4 br = ''.join(bro) show_output.insert(END, br) show_output.insert(END, '\n') elif f_len > 3 and l_len == 3: f_4 = f4(f_name) l_3 = l3(l_name) bro = f_4 + l_3 br = ''.join(bro) show_output.insert(END, br) show_output.insert(END, '\n') elif f_len > 3 and l_len > 3: f_4 = f4(f_name) l_4 = l4(l_name) bro = f_4 + l_4 br = ''.join(bro) show_output.insert(END, br) show_output.insert(END, '\n') else: pass if t.time() > t_end: def exp_logic(): exp_file = filedialog.askopenfilename(filetypes=(("Text files", "*.txt"), ("all files", "*.*"))) exp = open(exp_file, 'w') ow = 'Overwrite File?' ye = "Exporting names to this file will overwrite all of it's previous content. Do you wish to proceed?" res = messagebox.askyesno(ow, ye) if res is True: temp = show_output.get(1.0, END) exp.write(temp) exp.close() else: exp.close() def dupes(): show_output.config(state='normal') string = "" temp_str = show_output.get(1.0, END) string += temp_str string = string.splitlines() my_list = list(dict.fromkeys(string)) show_output.delete(1.0, END) for name_ in my_list: show_output.insert(END, name_) show_output.insert(END, '\n') show_output.config(state='disabled') dp_space = Label(window, height=1, bg='coral') dp_space.grid(column=1, row=13) dp = Button(window, text='Remove Duplicates', bg='coral', fg='Black', font=('Arial Bold', 11)) dp.config(command=dupes) dp.grid(column=1, row=14) txt_t = 'Export names as Text file' export = Button(window, text=txt_t, bg='coral', fg='Black', font=('Arial Bold', 11), command=exp_logic) export.grid(column=1, row=16) messagebox.showinfo('Operation Ended!', 'Names have been generated!') # space6 = Label(window, height=1, bg='coral') # space6.grid(column=1, row=17) show_output.config(state='disabled') gen_button.config(state='normal', command=on_gen) var = IntVar() var.set(5) space4 = Label(window, height=1, bg='coral') space4.grid(column=1, row=9) time = Spinbox(window, from_=1, to=100, width=10, textvariable=var) time.grid(column=1, row=10) space5 = Label(window, height=1, bg='coral') space5.grid(column=1, row=15)
def createWidgets(self): # Tab Control introduced here -------------------------------------- tabControl = ttk.Notebook(self.win) # Create Tab Control tab1 = ttk.Frame(tabControl) # Create a tab # tabControl.add(tab1, text='MySQL') # Add the tab -- COMMENTED OUT FOR CH08 tab2 = ttk.Frame(tabControl) # Add a second tab tabControl.add(tab2, text='Widgets') # Make second tab visible tabControl.pack(expand=1, fill="both") # Pack to make visible # ~ Tab Control introduced here ----------------------------------------- # We are creating a container frame to hold all other widgets self.mySQL = ttk.LabelFrame(tab1, text=' Python Database ') self.mySQL.grid(column=0, row=0, padx=8, pady=4) # Creating a Label ttk.Label(self.mySQL, text="Book Title:").grid(column=0, row=0, sticky='W') # Adding a Textbox Entry widget book = tk.StringVar() self.bookTitle = ttk.Entry(self.mySQL, width=34, textvariable=book) self.bookTitle.grid(column=0, row=1, sticky='W') # Adding a Textbox Entry widget book1 = tk.StringVar() self.bookTitle1 = ttk.Entry(self.mySQL, width=34, textvariable=book1) self.bookTitle1.grid(column=0, row=2, sticky='W') # Adding a Textbox Entry widget book2 = tk.StringVar() self.bookTitle2 = ttk.Entry(self.mySQL, width=34, textvariable=book2) self.bookTitle2.grid(column=0, row=3, sticky='W') # Creating a Label ttk.Label(self.mySQL, text="Page:").grid(column=1, row=0, sticky='W') # Adding a Textbox Entry widget page = tk.StringVar() self.pageNumber = ttk.Entry(self.mySQL, width=6, textvariable=page) self.pageNumber.grid(column=1, row=1, sticky='W') # Adding a Textbox Entry widget page = tk.StringVar() self.pageNumber1 = ttk.Entry(self.mySQL, width=6, textvariable=page) self.pageNumber1.grid(column=1, row=2, sticky='W') # Adding a Textbox Entry widget page = tk.StringVar() self.pageNumber2 = ttk.Entry(self.mySQL, width=6, textvariable=page) self.pageNumber2.grid(column=1, row=3, sticky='W') # Adding a Button self.action = ttk.Button(self.mySQL, text="Insert Quote", command=self.callBacks.insertQuote) self.action.grid(column=2, row=1) # Adding a Button self.action1 = ttk.Button(self.mySQL, text="Get Quotes", command=self.callBacks.getQuote) self.action1.grid(column=2, row=2) # Adding a Button self.action2 = ttk.Button(self.mySQL, text="Mody Quote", command=self.callBacks.modifyQuote) self.action2.grid(column=2, row=3) # Add some space around each widget for child in self.mySQL.winfo_children(): child.grid_configure(padx=2, pady=4) quoteFrame = ttk.LabelFrame(tab1, text=' Book Quotation ') quoteFrame.grid(column=0, row=1, padx=8, pady=4) # Using a scrolled Text control quoteW = 40 quoteH = 6 self.quote = scrolledtext.ScrolledText(quoteFrame, width=quoteW, height=quoteH, wrap=tk.WORD) self.quote.grid(column=0, row=8, sticky='WE', columnspan=3) # Add some space around each widget for child in quoteFrame.winfo_children(): child.grid_configure(padx=2, pady=4) #====================================================================================================== # Tab Control 2 #====================================================================================================== # We are creating a container frame to hold all other widgets -- Tab2 self.widgetFrame = ttk.LabelFrame(tab2, text=self.i18n.WIDGET_LABEL) self.widgetFrame.grid(column=0, row=0, padx=8, pady=4) # Creating three checkbuttons self.chVarDis = tk.IntVar() self.check1 = tk.Checkbutton(self.widgetFrame, text=self.i18n.disabled, variable=self.chVarDis, state='disabled') self.check1.select() self.check1.grid(column=0, row=0, sticky=tk.W) self.chVarUn = tk.IntVar() self.check2 = tk.Checkbutton(self.widgetFrame, text=self.i18n.unChecked, variable=self.chVarUn) self.check2.deselect() self.check2.grid(column=1, row=0, sticky=tk.W) self.chVarEn = tk.IntVar() self.check3 = tk.Checkbutton(self.widgetFrame, text=self.i18n.toggle, variable=self.chVarEn) self.check3.deselect() self.check3.grid(column=2, row=0, sticky=tk.W) # trace the state of the two checkbuttons self.chVarUn.trace( 'w', lambda unused0, unused1, unused2: self.callBacks.checkCallback()) self.chVarEn.trace( 'w', lambda unused0, unused1, unused2: self.callBacks.checkCallback()) # self.chVarUn.trace('w', lambda unused0, unused1, unused2 : self.checkCallback()) # <= bug missing callBacks # self.chVarEn.trace('w', lambda unused0, unused1, unused2 : self.checkCallback()) # Radiobutton list colors = self.i18n.colors self.radVar = tk.IntVar() # Selecting a non-existing index value for radVar self.radVar.set(99) # Creating all three Radiobutton widgets within one loop for col in range(3): self.curRad = 'rad' + str(col) self.curRad = tk.Radiobutton(self.widgetFrame, text=colors[col], variable=self.radVar, value=col, command=self.callBacks.radCall) self.curRad.grid(column=col, row=6, sticky=tk.W, columnspan=3) # And now adding tooltips tt.create_ToolTip(self.curRad, 'This is a Radiobutton control.') # Create a container to hold labels labelsFrame = ttk.LabelFrame(self.widgetFrame, text=self.i18n.labelsFrame) labelsFrame.grid(column=0, row=7, pady=6) # Place labels into the container element - vertically ttk.Label(labelsFrame, text=self.i18n.chooseNumber).grid(column=0, row=0) self.lbl2 = tk.StringVar() self.lbl2.set(self.i18n.label2) ttk.Label(labelsFrame, textvariable=self.lbl2).grid(column=0, row=1) # Add some space around each label for child in labelsFrame.winfo_children(): child.grid_configure(padx=6, pady=1) number = tk.StringVar() self.combo = ttk.Combobox(self.widgetFrame, width=12, textvariable=number) self.combo['values'] = (1, 2, 4, 42, 100) self.combo.grid(column=1, row=7, sticky=tk.W) self.combo.current(0) self.combo.bind('<<ComboboxSelected>>', self.callBacks._combo) # Adding a Spinbox widget using a set of values self.spin = Spinbox(self.widgetFrame, values=(1, 2, 4, 42, 100), width=5, bd=8, command=self.callBacks._spin) self.spin.grid(column=2, row=7, sticky='W,', padx=6, pady=1) # Using a scrolled Text control scrolW = 40 scrolH = 1 self.scr = scrolledtext.ScrolledText(self.widgetFrame, width=scrolW, height=scrolH, wrap=tk.WORD) self.scr.grid(column=0, row=8, sticky='WE', columnspan=3) # Adding a TZ Button self.allTZs = ttk.Button(self.widgetFrame, text=self.i18n.timeZones, command=self.callBacks.allTimeZones) self.allTZs.grid(column=0, row=9, sticky='WE') # Adding local TZ Button self.localTZ = ttk.Button(self.widgetFrame, text=self.i18n.localZone, command=self.callBacks.localZone) self.localTZ.grid(column=1, row=9, sticky='WE') # Adding getTime TZ Button self.dt = ttk.Button(self.widgetFrame, text=self.i18n.getTime, command=self.callBacks.getDateTime) self.dt.grid(column=2, row=9, sticky='WE') # Create Manage Files Frame ------------------------------------------------ mngFilesFrame = ttk.LabelFrame(tab2, text=self.i18n.mgrFiles) mngFilesFrame.grid(column=0, row=1, sticky='WE', padx=10, pady=5) # Button Callback def getFileName(): print('hello from getFileName') fDir = path.dirname(__file__) fName = fd.askopenfilename(parent=self.win, initialdir=fDir) print(fName) self.fileEntry.config(state='enabled') self.fileEntry.delete(0, tk.END) self.fileEntry.insert(0, fName) if len(fName) > self.entryLen: self.fileEntry.config(width=len(fName) + 3) # Add Widgets to Manage Files Frame lb = ttk.Button(mngFilesFrame, text=self.i18n.browseTo, command=getFileName) lb.grid(column=0, row=0, sticky=tk.W) #----------------------------------------------------- file = tk.StringVar() self.entryLen = scrolW - 4 self.fileEntry = ttk.Entry(mngFilesFrame, width=self.entryLen, textvariable=file) self.fileEntry.grid(column=1, row=0, sticky=tk.W) #----------------------------------------------------- logDir = tk.StringVar() self.netwEntry = ttk.Entry(mngFilesFrame, width=self.entryLen, textvariable=logDir) self.netwEntry.grid(column=1, row=1, sticky=tk.W) def copyFile(): import shutil src = self.fileEntry.get() file = src.split('/')[-1] dst = self.netwEntry.get() + '\\' + file try: shutil.copy(src, dst) mBox.showinfo('Copy File to Network', 'Succes: File copied.') except FileNotFoundError as err: mBox.showerror('Copy File to Network', '*** Failed to copy file! ***\n\n' + str(err)) except Exception as ex: mBox.showerror('Copy File to Network', '*** Failed to copy file! ***\n\n' + str(ex)) cb = ttk.Button(mngFilesFrame, text=self.i18n.copyTo, command=copyFile) cb.grid(column=0, row=1, sticky=tk.E) # Add some space around each label for child in mngFilesFrame.winfo_children(): child.grid_configure(padx=6, pady=6) # Creating a Menu Bar ========================================================== menuBar = Menu(tab1) self.win.config(menu=menuBar) # Add menu items fileMenu = Menu(menuBar, tearoff=0) fileMenu.add_command(label=self.i18n.new) fileMenu.add_separator() fileMenu.add_command(label=self.i18n.exit, command=self.callBacks._quit) menuBar.add_cascade(label=self.i18n.file, menu=fileMenu) # Add another Menu to the Menu Bar and an item helpMenu = Menu(menuBar, tearoff=0) helpMenu.add_command(label=self.i18n.about) menuBar.add_cascade(label=self.i18n.help, menu=helpMenu) # Change the main windows icon self.win.iconbitmap('pyc.ico') # Using tkinter Variable Classes strData = tk.StringVar() strData.set('Hello StringVar') # It is not necessary to create a tk.StringVar() strData = tk.StringVar() strData = self.spin.get() # Place cursor into name Entry self.bookTitle.focus() # Add a Tooltip to the Spinbox tt.create_ToolTip(self.spin, 'This is a Spin control.') # Add Tooltips to more widgets tt.create_ToolTip(self.bookTitle, 'This is an Entry control.') tt.create_ToolTip(self.action, 'This is a Button control.') tt.create_ToolTip(self.scr, 'This is a ScrolledText control.')
class OOP(): def __init__(self): # Create instance self.win = tk.Tk() # Add a title self.win.title("Python GUI") self.createWidgets() # Button callback def clickMe(self): self.action.configure(text='Hello ' + self.name.get()) # Button callback Clear Text def clearScrol(self): self.scr.delete('1.0', tk.END) # Spinbox callback def _spin(self): value = self.spin.get() print(value) self.scr.insert(tk.INSERT, value + '\n') # Checkbox callback def checkCallback(self, *ignoredArgs): # only enable one checkbutton if self.chVarUn.get(): self.check3.configure(state='disabled') else: self.check3.configure(state='normal') if self.chVarEn.get(): self.check2.configure(state='disabled') else: self.check2.configure(state='normal') # Radiobutton callback function def radCall(self): radSel = self.radVar.get() if radSel == 0: self.monty2.configure(text='Blue') elif radSel == 1: self.monty2.configure(text='Gold') elif radSel == 2: self.monty2.configure(text='Red') # Exit GUI cleanly def _quit(self): self.win.quit() self.win.destroy() exit() def usingGlobal(self): GLOBAL_CONST = 777 print(GLOBAL_CONST) ##################################################################################### def createWidgets(self): # Tab Control introduced here -------------------------------------- tabControl = ttk.Notebook(self.win) # Create Tab Control tab1 = ttk.Frame(tabControl) # Create a tab tabControl.add(tab1, text='Tab 1') # Add the tab tab2 = ttk.Frame(tabControl) # Add a second tab tabControl.add(tab2, text='Tab 2') # Make second tab visible tabControl.pack(expand=1, fill="both") # Pack to make visible # ~ Tab Control introduced here ----------------------------------------- # We are creating a container frame to hold all other widgets self.monty = ttk.LabelFrame(tab1, text=' Mighty Python ') self.monty.grid(column=0, row=0, padx=8, pady=4) # Changing our Label ttk.Label(self.monty, text="Enter a name:").grid(column=0, row=0, sticky='W') # Adding a Textbox Entry widget self.name = tk.StringVar() nameEntered = ttk.Entry(self.monty, width=12, textvariable=self.name) nameEntered.grid(column=0, row=1, sticky='W') # Adding a Button self.action = ttk.Button(self.monty, text="Click Me!", command=self.clickMe) self.action.grid(column=2, row=1) ttk.Label(self.monty, text="Choose a number:").grid(column=1, row=0) number = tk.StringVar() numberChosen = ttk.Combobox(self.monty, width=12, textvariable=number) numberChosen['values'] = (1, 2, 4, 42, 100) numberChosen.grid(column=1, row=1) numberChosen.current(0) # Adding a Spinbox widget using a set of values self.spin = Spinbox(self.monty, values=(1, 2, 4, 42, 100), width=5, bd=8, command=self._spin) self.spin.grid(column=0, row=2) # Using a scrolled Text control scrolW = 30 scrolH = 3 self.scr = scrolledtext.ScrolledText(self.monty, width=scrolW, height=scrolH, wrap=tk.WORD) self.scr.grid(column=0, row=3, sticky='WE', columnspan=3) # Tab Control 2 refactoring ----------------------------------------- # We are creating a container frame to hold all other widgets -- Tab2 self.monty2 = ttk.LabelFrame(tab2, text=' Holy Grail ') self.monty2.grid(column=0, row=0, padx=8, pady=4) # Creating three checkbuttons chVarDis = tk.IntVar() check1 = tk.Checkbutton(self.monty2, text="Disabled", variable=chVarDis, state='disabled') check1.select() check1.grid(column=0, row=0, sticky=tk.W) self.chVarUn = tk.IntVar() self.check2 = tk.Checkbutton(self.monty2, text="UnChecked", variable=self.chVarUn) self.check2.deselect() self.check2.grid(column=1, row=0, sticky=tk.W) self.chVarEn = tk.IntVar() self.check3 = tk.Checkbutton(self.monty2, text="Toggle", variable=self.chVarEn) self.check3.deselect() self.check3.grid(column=2, row=0, sticky=tk.W) # trace the state of the two checkbuttons self.chVarUn.trace( 'w', lambda unused0, unused1, unused2: self.checkCallback()) self.chVarEn.trace( 'w', lambda unused0, unused1, unused2: self.checkCallback()) # ~ Tab Control 2 refactoring ----------------------------------------- # Radiobutton list colors = ["Blue", "Gold", "Red"] self.radVar = tk.IntVar() # Selecting a non-existing index value for radVar self.radVar.set(99) # Creating all three Radiobutton widgets within one loop for col in range(3): curRad = 'rad' + str(col) curRad = tk.Radiobutton(self.monty2, text=colors[col], variable=self.radVar, value=col, command=self.radCall) curRad.grid(column=col, row=6, sticky=tk.W, columnspan=3) # And now adding tooltips ToolTip(curRad, 'This is a Radiobutton control.') # Create a container to hold labels labelsFrame = ttk.LabelFrame(self.monty2, text=' Labels in a Frame ') labelsFrame.grid(column=0, row=7) # Place labels into the container element - vertically ttk.Label(labelsFrame, text="Label1").grid(column=0, row=0) ttk.Label(labelsFrame, text="Label2").grid(column=0, row=1) # Add some space around each label for child in labelsFrame.winfo_children(): child.grid_configure(padx=8) # Creating a Menu Bar menuBar = Menu(tab1) self.win.config(menu=menuBar) # Add menu items fileMenu = Menu(menuBar, tearoff=0) fileMenu.add_command(label="New") fileMenu.add_separator() fileMenu.add_command(label="Exit", command=self._quit) menuBar.add_cascade(label="File", menu=fileMenu) # Add another Menu to the Menu Bar and an item helpMenu = Menu(menuBar, tearoff=0) helpMenu.add_command(label="About") menuBar.add_cascade(label="Help", menu=helpMenu) # Change the main windows icon self.win.iconbitmap('pyc.ico') # Using tkinter Variable Classes strData = tk.StringVar() strData.set('Hello StringVar') print(strData.get()) # Default tkinter Variable Classes intData = tk.IntVar() print(intData.get()) print(tk.DoubleVar()) print(tk.BooleanVar()) # It is not necessary to create a tk.StringVar() strData = tk.StringVar() strData = self.spin.get() print("Hello " + strData) # Printing the Global works print(GLOBAL_CONST) # call method self.usingGlobal() # Place cursor into name Entry nameEntered.focus() # Add a Tooltip to the Spinbox ToolTip(self.spin, 'This is a Spin control.') # Add Tooltips to more widgets ToolTip(nameEntered, 'This is an Entry control.') ToolTip(self.action, 'This is a Button control.') ToolTip(self.scr, 'This is a ScrolledText control.')
ttk.Label(outset, text="資料分組 : ").grid(column=0, row=2, sticky='W') scr = tk.StringVar() scr.set(10) # Spinbox callback def _spin(): value = spin.get() #print(value) spin = Spinbox(outset, from_=1, to=100, width=5, bd=8, command=_spin, increment=5, textvariable=scr) spin.grid(column=1, row=2) ttk.Label(outset, text="(可以自行輸入1-100整數)").grid(column=1, row=3, columnspan=2, sticky=tk.W) def storePath(): path_ = tk.filedialog.askdirectory() storepath.set(path_)
def updategui(self, halfclean=False, fullclean=False): if self.curmode == self.optionCreate: try: print(self.optionpostmodevar.get()) if self.optionpostmodevar.get() == "url": self.entryText.delete("1.0", "end") self.labelText.grid_forget() self.entryText.grid_forget() self.labelURL.grid(row=8, column=0, columnspan=30) self.entryURL.grid(row=9, column=0, columnspan=12, pady=10) if self.optionpostmodevar.get() == "text": self.entryURL.delete(0, "end") self.labelURL.grid_forget() self.entryURL.grid_forget() self.labelText.grid(row=8, column=0, columnspan=30) self.entryText.configure(width=40, height=8) self.entryText.grid(row=9, column=0, columnspan=12) except AttributeError: pass if fullclean == True: print("Cleaning GUI") for item in self.labellist: item.grid_forget() for item in self.entrylist: item.grid_forget() for item in self.verifylist: item.grid_forget() for item in self.misclist: item.grid_forget() self.labellist = [] self.entrylist = [] self.verifylist = [] self.misclist = [] if self.curmode == self.optionCreate: self.newrowindex = 6 self.labelSubreddit = Label(self, text="Subreddit: /r/") self.labelTitle = Label(self, text="Post title: ") self.entrySubreddit = Entry(self) self.entryTitle = Entry(self) self.labelHH = Label(self, text="Schedule time (Local timezone):") nowlist = datetime.datetime.strftime(datetime.datetime.now(), "%B %d %Y %H %M").split() self.entryMo = Spinbox( self, width=9, values=( "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", ), ) self.entryMo.delete(0, "end") self.entryMo.insert(0, nowlist[0]) self.entryDa = Spinbox(self, width=2, from_=1, to=31) self.entryDa.delete(0, "end") self.entryDa.insert(0, nowlist[1]) self.entryYr = Spinbox(self, width=4, from_=2014, to=2500) self.entryYr.delete(0, "end") self.entryYr.insert(0, nowlist[2]) self.entryHH = Spinbox(self, from_=0, to=23, width=2) self.entryHH.delete(0, "end") self.entryHH.insert(0, nowlist[3]) self.entryMM = Spinbox(self, from_=0, to=59, width=2) self.entryMM.delete(0, "end") self.entryMM.insert(0, nowlist[4]) self.buttonAddentry = Button( self, text="Save", command=lambda: self.addentrytobase( self.entrySubreddit.get(), self.entryTitle.get(), mode=self.optionpostmodevar.get() ), ) self.misclist.append(self.labelSubreddit) self.misclist.append(self.entrySubreddit) self.misclist.append(self.labelHH) self.misclist.append(self.entryHH) self.misclist.append(self.entryMM) self.misclist.append(self.entryMo) self.misclist.append(self.entryDa) self.misclist.append(self.entryYr) self.misclist.append(self.labelTitle) self.misclist.append(self.entryTitle) self.misclist.append(self.buttonAddentry) self.misclist.append(self.optionpostmode) self.misclist.append(self.labelText) self.misclist.append(self.entryText) self.misclist.append(self.labelURL) self.misclist.append(self.entryURL) self.labelSubreddit.grid(row=2, column=0, sticky="e") self.labelTitle.grid(row=3, column=0, sticky="e") self.entrySubreddit.grid(row=2, column=1, columnspan=3, sticky="w") self.entryTitle.grid(row=3, column=1, columnspan=3, sticky="w") self.entryMo.grid(row=4, column=1, sticky="e") self.entryDa.grid(row=4, column=2) self.entryYr.grid(row=4, column=3) self.labelHH.grid(row=4, column=0, sticky="se", pady=5) self.entryHH.grid(row=5, column=1, sticky="e") self.entryMM.grid(row=5, column=2, sticky="w") self.optionpostmode.grid(row=6, column=0, columnspan=20, pady=10) self.buttonAddentry.grid(row=200, column=0, columnspan=20) if self.curmode == self.optionUpcoming: self.cur.execute("SELECT * FROM upcoming") dobutton = True if self.curmode == self.optionPast: self.cur.execute("SELECT * FROM past") dobutton = False if self.curmode == self.optionPast or self.curmode == self.optionUpcoming: self.listboxId = Listbox(self) self.listboxId.configure(width=118, height=20, font=("Courier 8")) self.misclist.append(self.listboxId) self.listboxScroller = Scrollbar(self, orient="horizontal", command=self.listboxId.xview) self.listboxScroller.grid(row=4, column=0, columnspan=900) self.listboxId.grid(row=3, column=0, columnspan=10) self.listboxId.configure(xscrollcommand=self.listboxScroller.set) self.misclist.append(self.listboxScroller) self.buttonPrinter = Button(self, text="Print to .txt file") if self.curmode == self.optionPast: self.buttonPrinter.configure(command=lambda: self.printbasetofile("past")) if self.curmode == self.optionUpcoming: self.buttonPrinter.configure(command=lambda: self.printbasetofile("upcoming")) self.buttonPrinter.grid(row=6, column=0, columnspan=90) self.misclist.append(self.buttonPrinter) if dobutton == True: self.entryDelete = Entry(self) self.buttonDelete = Button( self, text="Delete Item: ", command=lambda: self.dropentryfrombase(self.entryDelete.get()) ) self.buttonDelete.grid(row=5, column=0, sticky="e") self.entryDelete.grid(row=5, column=1, sticky="w") self.misclist.append(self.entryDelete) self.misclist.append(self.buttonDelete) fetched = self.cur.fetchall() for item in fetched: d = datetime.datetime.fromtimestamp(item[2]) info = datetime.datetime.strftime(d, "%b %d %H:%M") if item[4] == "": infx = item[5] if item[5] == "": infx = item[4] if self.curmode == self.optionPast: infy = "." + item[6] else: infy = "" self.listboxId.insert( "end", item[0] + "." * (6 - len(item[0])) + item[1][:10] + "." * (12 - len(item[1][:10])) + info + "." * (15 - len(info[:14])) + item[3][:18] + "." * (20 - len(item[3][:14])) + infx[:45] + "." * (47 - len(infx[:45])) + infy, )
def createWidgets(self): # Tab Control introduced here -------------------------------------- tabControl = ttk.Notebook(self.win) # Create Tab Control tab1 = ttk.Frame(tabControl) # Create a tab tabControl.add(tab1, text='Tab 1') # Add the tab tab2 = ttk.Frame(tabControl) # Add a second tab tabControl.add(tab2, text='Tab 2') # Make second tab visible tabControl.pack(expand=1, fill="both") # Pack to make visible # ~ Tab Control introduced here ----------------------------------------- # We are creating a container frame to hold all other widgets self.monty = ttk.LabelFrame(tab1, text=' Monty Python ') self.monty.grid(column=0, row=0, padx=8, pady=4) # Changing our Label ttk.Label(self.monty, text="Enter a name:").grid(column=0, row=0, sticky='W') # Adding a Textbox Entry widget self.name = tk.StringVar() nameEntered = ttk.Entry(self.monty, width=24, textvariable=self.name) nameEntered.grid(column=0, row=1, sticky='W') nameEntered.delete(0, tk.END) nameEntered.insert(0, '< default name >') # Adding a Button self.action = ttk.Button(self.monty, text="Click Me!", command=self.clickMe) self.action.grid(column=2, row=1) ttk.Label(self.monty, text="Choose a number:").grid(column=1, row=0) number = tk.StringVar() numberChosen = ttk.Combobox(self.monty, width=14, textvariable=number) numberChosen['values'] = (1, 2, 4, 42, 100) numberChosen.grid(column=1, row=1) numberChosen.current(0) # Adding a Spinbox widget using a set of values self.spin = Spinbox(self.monty, values=(1, 2, 4, 42, 100), width=5, bd=8, command=self._spin) self.spin.grid(column=0, row=2, sticky='W') # Using a scrolled Text control scrolW = 40 scrolH = 10 self.scr = scrolledtext.ScrolledText(self.monty, width=scrolW, height=scrolH, wrap=tk.WORD) self.scr.grid(column=0, row=3, sticky='WE', columnspan=3) # Tab Control 2 refactoring --------------------------------------------------- # We are creating a container frame to hold all other widgets -- Tab2 self.monty2 = ttk.LabelFrame(tab2, text=' The Snake ') self.monty2.grid(column=0, row=0, padx=8, pady=4) # Creating three checkbuttons chVarDis = tk.IntVar() check1 = tk.Checkbutton(self.monty2, text="Disabled", variable=chVarDis, state='disabled') check1.select() check1.grid(column=0, row=0, sticky=tk.W) self.chVarUn = tk.IntVar() self.check2 = tk.Checkbutton(self.monty2, text="UnChecked", variable=self.chVarUn) self.check2.deselect() self.check2.grid(column=1, row=0, sticky=tk.W) self.chVarEn = tk.IntVar() self.check3 = tk.Checkbutton(self.monty2, text="Toggle", variable=self.chVarEn) self.check3.deselect() self.check3.grid(column=2, row=0, sticky=tk.W) # trace the state of the two checkbuttons self.chVarUn.trace( 'w', lambda unused0, unused1, unused2: self.checkCallback()) self.chVarEn.trace( 'w', lambda unused0, unused1, unused2: self.checkCallback()) # ~ Tab Control 2 refactoring ----------------------------------------- # Radiobutton list colors = ["Blue", "Gold", "Red"] self.radVar = tk.IntVar() # Selecting a non-existing index value for radVar self.radVar.set(99) # Creating all three Radiobutton widgets within one loop for col in range(3): curRad = 'rad' + str(col) curRad = tk.Radiobutton(self.monty2, text=colors[col], variable=self.radVar, value=col, command=self.radCall) curRad.grid(column=col, row=6, sticky=tk.W, columnspan=3) # And now adding tooltips tt.createToolTip(curRad, 'This is a Radiobutton control.') # Create a container to hold labels labelsFrame = ttk.LabelFrame(self.monty2, text=' Labels in a Frame ') labelsFrame.grid(column=0, row=7) # Place labels into the container element - vertically ttk.Label(labelsFrame, text="Label1").grid(column=0, row=0) ttk.Label(labelsFrame, text="Label2").grid(column=0, row=1) # Add some space around each label for child in labelsFrame.winfo_children(): child.grid_configure(padx=8) # Create Manage Files Frame ------------------------------------------------ mngFilesFrame = ttk.LabelFrame(tab2, text=' Manage Files: ') mngFilesFrame.grid(column=0, row=1, sticky='WE', padx=10, pady=5) # Button Callback def getFileName(): print('hello from getFileName') fDir = path.dirname(__file__) fName = fd.askopenfilename(parent=self.win, initialdir=fDir) print(fName) self.fileEntry.config(state='enabled') self.fileEntry.delete(0, tk.END) self.fileEntry.insert(0, fName) if len(fName) > self.entryLen: self.fileEntry.config(width=len(fName) + 3) # Add Widgets to Manage Files Frame lb = ttk.Button(mngFilesFrame, text="Browse to File...", command=getFileName) lb.grid(column=0, row=0, sticky=tk.W) #----------------------------------------------------- file = tk.StringVar() self.entryLen = scrolW - 4 self.fileEntry = ttk.Entry(mngFilesFrame, width=self.entryLen, textvariable=file) self.fileEntry.grid(column=1, row=0, sticky=tk.W) #----------------------------------------------------- logDir = tk.StringVar() self.netwEntry = ttk.Entry(mngFilesFrame, width=self.entryLen, textvariable=logDir) self.netwEntry.grid(column=1, row=1, sticky=tk.W) def copyFile(): import shutil src = self.fileEntry.get() file = src.split('/')[-1] dst = self.netwEntry.get() + '\\' + file try: shutil.copy(src, dst) mBox.showinfo('Copy File to Network', 'Succes: File copied.') except FileNotFoundError as err: mBox.showerror('Copy File to Network', '*** Failed to copy file! ***\n\n' + str(err)) except Exception as ex: mBox.showerror('Copy File to Network', '*** Failed to copy file! ***\n\n' + str(ex)) cb = ttk.Button(mngFilesFrame, text="Copy File To : ", command=copyFile) cb.grid(column=0, row=1, sticky=tk.E) # Add some space around each label for child in mngFilesFrame.winfo_children(): child.grid_configure(padx=6, pady=6) # Creating a Menu Bar ========================================================== menuBar = Menu(tab1) self.win.config(menu=menuBar) # Add menu items fileMenu = Menu(menuBar, tearoff=0) fileMenu.add_command(label="New") fileMenu.add_separator() fileMenu.add_command(label="Exit", command=self._quit) menuBar.add_cascade(label="File", menu=fileMenu) # Add another Menu to the Menu Bar and an item helpMenu = Menu(menuBar, tearoff=0) helpMenu.add_command(label="About") menuBar.add_cascade(label="Help", menu=helpMenu) # Change the main windows icon self.win.iconbitmap(r'C:\Python34\DLLs\pyc.ico') # Using tkinter Variable Classes strData = tk.StringVar() strData.set('Hello StringVar') # It is not necessary to create a tk.StringVar() strData = tk.StringVar() strData = self.spin.get() # Place cursor into name Entry # nameEntered.focus() # Set focus to Tab 2 # tabControl.select(1) # Add a Tooltip to the Spinbox tt.createToolTip(self.spin, 'This is a Spin control.') # Add Tooltips to more widgets tt.createToolTip(nameEntered, 'This is an Entry control.') tt.createToolTip(self.action, 'This is a Button control.') tt.createToolTip(self.scr, 'This is a ScrolledText control.')
def createWidgets(self): '''Create and align widgets''' top = self.winfo_toplevel() top.rowconfigure(0, weight=1) top.columnconfigure(0, weight=1) self.rowconfigure(0, weight=1) self.columnconfigure(0, weight=1) self.passwordout = StringVar() self.passwordout.set('- No password generated -') self.isnew = IntVar() ttitle = Label(self, text=versionStr, font=self.getFont(4)) wisnew = Checkbutton(self, height=2, font=self.getFont(), text=('This is a new password, that I have not ' 'used before'), variable=self.isnew, command=self.toggleCheck) tlabel = Label(self, text='Label', font=self.getFont(2)) tpasswordin1 = Label(self, text='Password', font=self.getFont(2)) tpasswordin2 = Label(self, text='Password (again)', font=self.getFont(2)) tlength = Label(self, text='Length', font=self.getFont(2)) talgorithm = Label(self, text='Algorithm', font=self.getFont(2)) tsequence = Label(self, text='Sequence #', font=self.getFont(2)) self.label = ttk.Combobox(self, width=27, font=self.getFont(), postcommand=self.filterLabels) self.passwordin1 = Entry(self, width=27, font=self.getFont(), show="*") self.passwordin2 = Entry(self, width=27, font=self.getFont(), show="*", state=DISABLED) length = Spinbox(self, width=3, font=self.getFont, from_=9, to=171, textvariable=self.lengthVar) self.algorithm = ttk.Combobox(self, width=27, font=self.getFont(), values=algos.algorithms) sequence = Spinbox(self, width=3, font=self.getFont, from_=1, to=sys.maxsize, textvariable=self.sequenceVar) genbutton = Button(self, text="Generate password", font=self.getFont(), command=self.validateAndShow, default="active") clrbutton = Button(self, text="Clear fields", font=self.getFont(), command=self.clearIO) self.result = Entry(self, font=self.getFont(4), textvariable=self.passwordout, state="readonly", fg="black", readonlybackground="gray") # Keybindings self.passwordin1.bind('<Return>', lambda e: genbutton.invoke()) self.passwordin2.bind('<Return>', lambda e: genbutton.invoke()) length.bind('<Return>', lambda e: genbutton.invoke()) self.algorithm.bind('<Return>', lambda e: genbutton.invoke()) sequence.bind('<Return>', lambda e: genbutton.invoke()) self.master.bind('<Control-q>', lambda e: self.quit()) self.master.bind('<Escape>', lambda e: self.reset()) self.label.bind('<<ComboboxSelected>>', self.labelSelected) self.label.bind('<FocusOut>', self.labelFocusOut) # Layout widgets in a grid ttitle.grid(row=0, column=0, sticky=N + S + E + W, columnspan=2) wisnew.grid(row=1, column=0, sticky=N + S + E + W, columnspan=2) tlabel.grid(row=2, column=0, sticky=N + S + W) self.label.grid(row=2, column=1, sticky=N + S + E + W) tpasswordin1.grid(row=3, column=0, sticky=N + S + W) self.passwordin1.grid(row=3, column=1, sticky=N + S + E + W) tpasswordin2.grid(row=4, column=0, sticky=N + S + W) self.passwordin2.grid(row=4, column=1, sticky=N + S + E + W) tlength.grid(row=5, column=0, sticky=N + S + W) length.grid(row=5, column=1, sticky=N + S + E + W) talgorithm.grid(row=6, column=0, sticky=N + S + W) self.algorithm.grid(row=6, column=1, sticky=N + S + E + W) tsequence.grid(row=7, column=0, sticky=N + S + W) sequence.grid(row=7, column=1, sticky=N + S + E + W) clrbutton.grid(row=8, column=0, sticky=N + S + E + W, columnspan=2) genbutton.grid(row=9, column=0, sticky=N + S + E + W, columnspan=2) self.result.grid(row=10, column=0, sticky=N + S + E + W, columnspan=2) # Initial values self.algorithm.set(self.settings.algorithm) # Initially, set focus on self.label self.label.focus_set()
class OOP(): def __init__(self): # Create instance self.win = tk.Tk() # Add a title self.win.title("Python GUI") # Disable resizing the window self.win.resizable(0, 0) # Create a Queue self.guiQueue = Queue() self.createWidgets() # populate Tab 2 Entries self.defaultFileEntries() # Start TCP/IP server in its own thread svrT = Thread(target=startServer, daemon=True) svrT.start() def defaultFileEntries(self): # populate Entry before making it read-only #self.fileEntry.config(state='readonly') self.fileEntry.delete(0, tk.END) #self.fileEntry.insert(0, fDir) self.fileEntry.insert(0, 'Z:\\') # bogus path # if len(fDir) > self.entryLen: # self.fileEntry.config(width=len(fDir) + 3) self.fileEntry.config(state='readonly') self.netwEntry.delete(0, tk.END) #self.netwEntry.insert(0, netDir) self.netwEntry.insert(0, 'Z:\\Backup') # bogus path # if len(netDir) > self.entryLen: # self.netwEntry.config(width=len(netDir) + 3) # Button callback def clickMe(self): self.action.configure(text='Hello ' + self.name.get()) # # Non-threaded code with sleep freezes the GUI # for idx in range(10): # sleep(5) # self.scr.insert(tk.INSERT, str(idx) + '\n') # # Threaded method does not freeze our GUI # self.createThread() # Passing in the current class instance (self) print(self) bq.writeToScrol(self) sleep(2) htmlData = url.getHtml() print(htmlData) self.scr.insert(tk.INSERT, htmlData) # Spinbox callback def _spin(self): value = self.spin.get() #print(value) self.scr.insert(tk.INSERT, value + '\n') # Checkbox callback def checkCallback(self, *ignoredArgs): # only enable one checkbutton if self.chVarUn.get(): self.check3.configure(state='disabled') else: self.check3.configure(state='normal') if self.chVarEn.get(): self.check2.configure(state='disabled') else: self.check2.configure(state='normal') # Radiobutton callback function def radCall(self): radSel = self.radVar.get() if radSel == 0: self.monty2.configure(text='Blue') elif radSel == 1: self.monty2.configure(text='Gold') elif radSel == 2: self.monty2.configure(text='Red') # Exit GUI cleanly def _quit(self): self.win.quit() self.win.destroy() exit() # def methodInAThread(self): # print('Hi, how are you?') # for idx in range(10): # sleep(5) # self.scr.insert(tk.INSERT, str(idx) + '\n') def methodInAThread(self, numOfLoops=10): for idx in range(numOfLoops): sleep(1) self.scr.insert(tk.INSERT, str(idx) + '\n') sleep(1) print('methodInAThread():', self.runT.isAlive()) # Running methods in Threads def createThread(self, num): self.runT = Thread(target=self.methodInAThread, args=[num]) self.runT.setDaemon(True) self.runT.start() print(self.runT) print('createThread():', self.runT.isAlive()) # textBoxes are the Consumers of Queue data writeT = Thread(target=self.useQueues, daemon=True) writeT.start() # Create Queue instance def useQueues(self): # guiQueue = Queue() # print(guiQueue) # for idx in range(10): # guiQueue.put('Message from a queue: ' + str(idx)) # while True: # print(guiQueue.get()) # Now using a class member Queue while True: qItem = self.guiQueue.get() print(qItem) self.scr.insert(tk.INSERT, qItem + '\n') ##################################################################################### def createWidgets(self): # Tab Control introduced here -------------------------------------- tabControl = ttk.Notebook(self.win) # Create Tab Control tab1 = ttk.Frame(tabControl) # Create a tab tabControl.add(tab1, text='Tab 1') # Add the tab tab2 = ttk.Frame(tabControl) # Add a second tab tabControl.add(tab2, text='Tab 2') # Make second tab visible tabControl.pack(expand=1, fill="both") # Pack to make visible # ~ Tab Control introduced here ----------------------------------------- # We are creating a container frame to hold all other widgets self.monty = ttk.LabelFrame(tab1, text=' Monty Python ') self.monty.grid(column=0, row=0, padx=8, pady=4) # Changing our Label ttk.Label(self.monty, text="Enter a name:").grid(column=0, row=0, sticky='W') # Adding a Textbox Entry widget self.name = tk.StringVar() nameEntered = ttk.Entry(self.monty, width=24, textvariable=self.name) nameEntered.grid(column=0, row=1, sticky='W') nameEntered.delete(0, tk.END) nameEntered.insert(0, '< default name >') # Adding a Button self.action = ttk.Button(self.monty, text="Click Me!", command=self.clickMe) self.action.grid(column=2, row=1) ttk.Label(self.monty, text="Choose a number:").grid(column=1, row=0) number = tk.StringVar() numberChosen = ttk.Combobox(self.monty, width=14, textvariable=number) numberChosen['values'] = (1, 2, 4, 42, 100) numberChosen.grid(column=1, row=1) numberChosen.current(0) # Adding a Spinbox widget using a set of values self.spin = Spinbox(self.monty, values=(1, 2, 4, 42, 100), width=5, bd=8, command=self._spin) self.spin.grid(column=0, row=2, sticky='W') # Using a scrolled Text control scrolW = 40 scrolH = 10 self.scr = scrolledtext.ScrolledText(self.monty, width=scrolW, height=scrolH, wrap=tk.WORD) self.scr.grid(column=0, row=3, sticky='WE', columnspan=3) # Tab Control 2 refactoring --------------------------------------------------- # We are creating a container frame to hold all other widgets -- Tab2 self.monty2 = ttk.LabelFrame(tab2, text=' The Snake ') self.monty2.grid(column=0, row=0, padx=8, pady=4) # Creating three checkbuttons chVarDis = tk.IntVar() check1 = tk.Checkbutton(self.monty2, text="Disabled", variable=chVarDis, state='disabled') check1.select() check1.grid(column=0, row=0, sticky=tk.W) self.chVarUn = tk.IntVar() self.check2 = tk.Checkbutton(self.monty2, text="UnChecked", variable=self.chVarUn) self.check2.deselect() self.check2.grid(column=1, row=0, sticky=tk.W) self.chVarEn = tk.IntVar() self.check3 = tk.Checkbutton(self.monty2, text="Toggle", variable=self.chVarEn) self.check3.deselect() self.check3.grid(column=2, row=0, sticky=tk.W) # trace the state of the two checkbuttons self.chVarUn.trace( 'w', lambda unused0, unused1, unused2: self.checkCallback()) self.chVarEn.trace( 'w', lambda unused0, unused1, unused2: self.checkCallback()) # ~ Tab Control 2 refactoring ----------------------------------------- # Radiobutton list colors = ["Blue", "Gold", "Red"] self.radVar = tk.IntVar() # Selecting a non-existing index value for radVar self.radVar.set(99) # Creating all three Radiobutton widgets within one loop for col in range(3): curRad = 'rad' + str(col) curRad = tk.Radiobutton(self.monty2, text=colors[col], variable=self.radVar, value=col, command=self.radCall) curRad.grid(column=col, row=6, sticky=tk.W, columnspan=3) # And now adding tooltips tt.createToolTip(curRad, 'This is a Radiobutton control.') # Create a container to hold labels labelsFrame = ttk.LabelFrame(self.monty2, text=' Labels in a Frame ') labelsFrame.grid(column=0, row=7) # Place labels into the container element - vertically ttk.Label(labelsFrame, text="Label1").grid(column=0, row=0) ttk.Label(labelsFrame, text="Label2").grid(column=0, row=1) # Add some space around each label for child in labelsFrame.winfo_children(): child.grid_configure(padx=8) # Create Manage Files Frame ------------------------------------------------ mngFilesFrame = ttk.LabelFrame(tab2, text=' Manage Files: ') mngFilesFrame.grid(column=0, row=1, sticky='WE', padx=10, pady=5) # Button Callback def getFileName(): print('hello from getFileName') fDir = path.dirname(__file__) fName = fd.askopenfilename(parent=self.win, initialdir=fDir) print(fName) self.fileEntry.config(state='enabled') self.fileEntry.delete(0, tk.END) self.fileEntry.insert(0, fName) if len(fName) > self.entryLen: self.fileEntry.config(width=len(fName) + 3) # Add Widgets to Manage Files Frame lb = ttk.Button(mngFilesFrame, text="Browse to File...", command=getFileName) lb.grid(column=0, row=0, sticky=tk.W) #----------------------------------------------------- file = tk.StringVar() self.entryLen = scrolW - 4 self.fileEntry = ttk.Entry(mngFilesFrame, width=self.entryLen, textvariable=file) self.fileEntry.grid(column=1, row=0, sticky=tk.W) #----------------------------------------------------- logDir = tk.StringVar() self.netwEntry = ttk.Entry(mngFilesFrame, width=self.entryLen, textvariable=logDir) self.netwEntry.grid(column=1, row=1, sticky=tk.W) def copyFile(): import shutil src = self.fileEntry.get() file = src.split('/')[-1] dst = self.netwEntry.get() + '\\' + file try: shutil.copy(src, dst) mBox.showinfo('Copy File to Network', 'Succes: File copied.') except FileNotFoundError as err: mBox.showerror('Copy File to Network', '*** Failed to copy file! ***\n\n' + str(err)) except Exception as ex: mBox.showerror('Copy File to Network', '*** Failed to copy file! ***\n\n' + str(ex)) cb = ttk.Button(mngFilesFrame, text="Copy File To : ", command=copyFile) cb.grid(column=0, row=1, sticky=tk.E) # Add some space around each label for child in mngFilesFrame.winfo_children(): child.grid_configure(padx=6, pady=6) # Creating a Menu Bar ========================================================== menuBar = Menu(tab1) self.win.config(menu=menuBar) # Add menu items fileMenu = Menu(menuBar, tearoff=0) fileMenu.add_command(label="New") fileMenu.add_separator() fileMenu.add_command(label="Exit", command=self._quit) menuBar.add_cascade(label="File", menu=fileMenu) # Add another Menu to the Menu Bar and an item helpMenu = Menu(menuBar, tearoff=0) helpMenu.add_command(label="About") menuBar.add_cascade(label="Help", menu=helpMenu) # Change the main windows icon self.win.iconbitmap(r'C:\Python34\DLLs\pyc.ico') # Using tkinter Variable Classes strData = tk.StringVar() strData.set('Hello StringVar') # It is not necessary to create a tk.StringVar() strData = tk.StringVar() strData = self.spin.get() # Place cursor into name Entry # nameEntered.focus() # Set focus to Tab 2 # tabControl.select(1) # Add a Tooltip to the Spinbox tt.createToolTip(self.spin, 'This is a Spin control.') # Add Tooltips to more widgets tt.createToolTip(nameEntered, 'This is an Entry control.') tt.createToolTip(self.action, 'This is a Button control.') tt.createToolTip(self.scr, 'This is a ScrolledText control.')
def createWidgets(self): tabControl= ttk.Notebook(self.win) tab1=ttk.Frame(tabControl) tabControl.add(tab1, text='Tab 1') tab2 = ttk.Frame(tabControl) tabControl.add(tab2, text='Tab 2') tab3 = ttk.Frame(tabControl) tabControl.add(tab3, text='Tab 3') tabControl.pack(expand=1, fill='both') tab3=tk.Frame(tab3,bg='blue') tab3.pack() for orangeColor in range(2): canvas = tk.Canvas(tab3, width=150,height=80,highlightthickness=0,bg='orange') canvas.grid(row=orangeColor,column=orangeColor) # create container to hold all widgets self.monty = ttk.LabelFrame(tab1,text=' Monty Python ') self.monty.grid(column=0,row=0,padx=8,pady=4) self.monty2 = ttk.LabelFrame(tab2,text=' The Snake ') self.monty2.grid(column=0,row=0,padx=8,pady=4) #Label ttk.Label(self.monty,text="Enter a name:").grid(column=0,row=0,sticky='W') #add a text box widget name = tk.StringVar() self.nameEntered = ttk.Entry(self.monty, width=12, textvariable=name) self.nameEntered.grid(column=0,row=1,sticky=tk.W) tt.createToolTip(self.nameEntered, 'This is an entry control') # combo box and label ttk.Label(self.monty, text='Choose a number:').grid(column=1, row=0) number = tk.StringVar() numberChosen = ttk.Combobox(self.monty, width=12, textvariable=number, state='readonly') numberChosen['values'] = (1,2,4,42,100) numberChosen.grid(column=1, row=1) numberChosen.current(0) # add a button action = ttk.Button(self.monty, text="Click Me!", command=self.clickMe) action.grid(column=2, row=1) #action.configure(state='disabled') #add check boxes chVarDis = tk.IntVar() check1 = tk.Checkbutton(self.monty2, text='Disabled',variable=chVarDis, state='disabled') check1.select() check1.grid(column=0,row=4, sticky=tk.W) chVarUn = tk.IntVar() check2 = tk.Checkbutton(self.monty2, text='UnChecked',variable=chVarUn) check2.deselect() check2.grid(column=1,row=4,sticky=tk.W) chVarEn = tk.IntVar() check3 = tk.Checkbutton(self.monty2, text='Enabled',variable=chVarEn) check3.select() check3.grid(column=2,row=4,sticky=tk.W) # Radiobutton list colors = ["Blue", "Gold", "Red"] #create three radio buttons self.radVar=tk.IntVar() self.radVar.set(99) for col in range(3): curRad = 'rad' + str(col) curRad = tk.Radiobutton(self.monty2, text=colors[col], variable=self.radVar, value = col, command=self.radCall) curRad.grid(column=col, row=5, sticky=tk.W) #add a spinbox self.spin = Spinbox(self.monty,from_=0,to=10,width=5,bd=8, command=self._spin) self.spin.grid(column=0,row=2) # add a tooltip tt.createToolTip(self.spin,'This is a Spin control.') spin2 = Spinbox(self.monty, values=(0,50,100),width=5,bd=10,command=self._spin,relief=tk.RIDGE) spin2.grid(column=1,row=2) # add scrolled text widget scrolW= 50 scrolH = 3 self.scr = scrolledtext.ScrolledText(self.monty, width=scrolW, height=scrolH, wrap=tk.WORD) self.scr.grid(column=0, sticky='WE',columnspan=3) #scr.grid(column=0, columnspan=3) tt.createToolTip(self.scr,'This is a ScrolledText widget.') # container to hold labels labelsFrame = ttk.LabelFrame(self.monty, text=' Labels in a Frame ') labelsFrame.grid(column=0,row=7,padx=20,pady=40) # place labels into the container ttk.Label(labelsFrame,text='Label1').grid(column=0,row=0) ttk.Label(labelsFrame,text='Label2').grid(column=0,row=1) ttk.Label(labelsFrame,text='Label3').grid(column=0,row=2) for child in labelsFrame.winfo_children(): child.grid_configure(padx=8,pady=4) # menu commands def _quit(self): self.win.quit() self.win.destroy() exit() #create menubar menuBar=Menu(self.win) self.win.config(menu=menuBar) # add menu items fileMenu = Menu(menuBar, tearoff=0) fileMenu.add_command(label='New') fileMenu.add_separator() fileMenu.add_command(label='Exit', command=_quit) menuBar.add_cascade(label='File',menu=fileMenu) helpMenu = Menu(menuBar,tearoff=0) helpMenu.add_command(label='About',command=self._msgBox) menuBar.add_cascade(label='Help',menu=helpMenu)
class NewPosterizeWindow(Toplevel): def __init__(self, name, master=None): super().__init__(master=master) self.set_basic(name) self.master.image.posterize(2) self.bind('<Configure>', lambda e: self.place_buttons()) def set_basic(self, name): self.overrideredirect(1) self.set_geometry() self.set_spinbox() self.set_save_closeButtons() self.title("Redukcja poziomów szarości {}".format(name)) def set_geometry(self): self.height = 30 parentX = self.master.winfo_rootx() parentY = self.master.winfo_rooty() parentHeight = self.master.winfo_height() parentWidth = self.master.winfo_width() self.geometry( '%dx%d+%d+%d' % (parentWidth, self.height, parentX, parentY + parentHeight + 2)) def set_spinbox(self): self.spinBox = Spinbox(self, command=lambda: self.update_preview(), from_=2, to=255, width=3, font=("Helvetica", 15), justify=LEFT) self.spinBox.place(relx=0.375, relwidth=0.25) self.spinBox.delete(0, "end") self.spinBox.insert(0, 2) def set_save_closeButtons(self): self.saveButton = Button(self, image=saveIcon, command=self.update_image) self.cancelButton = Button(self, image=closeIcon, command=self.cancel) self.saveButton.place(relx=1 - ((2 * self.height) / self.master.winfo_width()), relheight=1) self.cancelButton.place(relx=1 - (self.height / self.master.winfo_width()), relheight=1) def place_buttons(self): self.saveButton.place(relx=1 - ((2 * self.height) / self.master.winfo_width()), relheight=1, width=self.height) self.cancelButton.place(relx=1 - (self.height / self.master.winfo_width()), relheight=1, width=self.height) def update_preview(self): self.master.image.posterize(int(self.spinBox.get())) self.master.update_visible_image() def update_image(self): self.master.update_visible_image() self.master.image.copy = copy.deepcopy(self.master.image.cv2Image) self.master.image.fill_histogram() self.master.update_child_windows() self.master.manager.new_state(self.master.image.cv2Image) self.master.posterizeWindow = None self.destroy() def cancel(self): self.master.image.cv2Image = copy.deepcopy(self.master.image.copy) self.master.update_visible_image() self.master.image.fill_histogram() self.master.update_child_windows() self.master.posterizeWindow = None self.destroy()
class OOP(): def __init__(self): # Create instance self.win = tk.Tk() # Add a title self.win.title("Python GUI") # Disable resizing the window self.win.resizable(0,0) # Create a Queue self.guiQueue = Queue() self.createWidgets() # populate Tab 2 Entries self.defaultFileEntries() # create MySQL instance self.mySQL = MySQL() def defaultFileEntries(self): self.fileEntry.delete(0, tk.END) self.fileEntry.insert(0, 'Z:\\') # bogus path self.fileEntry.config(state='readonly') self.netwEntry.delete(0, tk.END) self.netwEntry.insert(0, 'Z:\\Backup') # bogus path # Combobox callback def _combo(self, val=0): value = self.combo.get() self.scr.insert(tk.INSERT, value + '\n') # Spinbox callback def _spin(self): value = self.spin.get() self.scr.insert(tk.INSERT, value + '\n') # Checkbox callback def checkCallback(self, *ignoredArgs): # only enable one checkbutton if self.chVarUn.get(): self.check3.configure(state='disabled') else: self.check3.configure(state='normal') if self.chVarEn.get(): self.check2.configure(state='disabled') else: self.check2.configure(state='normal') # Radiobutton callback function def radCall(self): radSel=self.radVar.get() if radSel == 0: self.mySQL2.configure(text=WIDGET_LABEL + 'in Blue') elif radSel == 1: self.mySQL2.configure(text=WIDGET_LABEL + 'in Gold') elif radSel == 2: self.mySQL2.configure(text=WIDGET_LABEL + 'in Red') # Exit GUI cleanly def _quit(self): self.win.quit() self.win.destroy() exit() def methodInAThread(self, numOfLoops=10): for idx in range(numOfLoops): sleep(1) self.scr.insert(tk.INSERT, str(idx) + '\n') sleep(1) print('methodInAThread():', self.runT.isAlive()) # Running methods in Threads def createThread(self, num): self.runT = Thread(target=self.methodInAThread, args=[num]) self.runT.setDaemon(True) self.runT.start() print(self.runT) print('createThread():', self.runT.isAlive()) # textBoxes are the Consumers of Queue data writeT = Thread(target=self.useQueues, daemon=True) writeT.start() # Create Queue instance def useQueues(self): # Now using a class member Queue while True: qItem = self.guiQueue.get() print(qItem) self.scr.insert(tk.INSERT, qItem + '\n') # Button callback def insertQuote(self): title = self.bookTitle.get() page = self.pageNumber.get() quote = self.quote.get(1.0, tk.END) print(title) print(quote) self.mySQL.insertBooks(title, page, quote) # Button callback def getQuote(self): allBooks = self.mySQL.showBooks() print(allBooks) self.quote.insert(tk.INSERT, allBooks) # Button callback def modifyQuote(self): raise NotImplementedError("This still needs to be implemented for the SQL command.") ##################################################################################### def createWidgets(self): # Tab Control introduced here -------------------------------------- tabControl = ttk.Notebook(self.win) # Create Tab Control tab1 = ttk.Frame(tabControl) # Create a tab tabControl.add(tab1, text='MySQL') # Add the tab tab2 = ttk.Frame(tabControl) # Add a second tab tabControl.add(tab2, text='Widgets') # Make second tab visible tabControl.pack(expand=1, fill="both") # Pack to make visible # ~ Tab Control introduced here ----------------------------------------- # We are creating a container frame to hold all other widgets self.mySQL = ttk.LabelFrame(tab1, text=' Python Database ') self.mySQL.grid(column=0, row=0, padx=8, pady=4) # Creating a Label ttk.Label(self.mySQL, text="Book Title:").grid(column=0, row=0, sticky='W') # Adding a Textbox Entry widget book = tk.StringVar() self.bookTitle = ttk.Entry(self.mySQL, width=34, textvariable=book) self.bookTitle.grid(column=0, row=1, sticky='W') # Adding a Textbox Entry widget book1 = tk.StringVar() self.bookTitle1 = ttk.Entry(self.mySQL, width=34, textvariable=book1) self.bookTitle1.grid(column=0, row=2, sticky='W') # Adding a Textbox Entry widget book2 = tk.StringVar() self.bookTitle2 = ttk.Entry(self.mySQL, width=34, textvariable=book2) self.bookTitle2.grid(column=0, row=3, sticky='W') # Creating a Label ttk.Label(self.mySQL, text="Page:").grid(column=1, row=0, sticky='W') # Adding a Textbox Entry widget page = tk.StringVar() self.pageNumber = ttk.Entry(self.mySQL, width=6, textvariable=page) self.pageNumber.grid(column=1, row=1, sticky='W') # Adding a Textbox Entry widget page = tk.StringVar() self.pageNumber1 = ttk.Entry(self.mySQL, width=6, textvariable=page) self.pageNumber1.grid(column=1, row=2, sticky='W') # Adding a Textbox Entry widget page = tk.StringVar() self.pageNumber2 = ttk.Entry(self.mySQL, width=6, textvariable=page) self.pageNumber2.grid(column=1, row=3, sticky='W') # Adding a Button self.action = ttk.Button(self.mySQL, text="Insert Quote", command=self.insertQuote) self.action.grid(column=2, row=1) # Adding a Button self.action1 = ttk.Button(self.mySQL, text="Get Quotes", command=self.getQuote) self.action1.grid(column=2, row=2) # Adding a Button self.action2 = ttk.Button(self.mySQL, text="Mody Quote", command=self.modifyQuote) self.action2.grid(column=2, row=3) # Add some space around each widget for child in self.mySQL.winfo_children(): child.grid_configure(padx=2, pady=4) quoteFrame = ttk.LabelFrame(tab1, text=' Book Quotation ') quoteFrame.grid(column=0, row=1, padx=8, pady=4) # Using a scrolled Text control quoteW = 40; quoteH = 6 self.quote = scrolledtext.ScrolledText(quoteFrame, width=quoteW, height=quoteH, wrap=tk.WORD) self.quote.grid(column=0, row=8, sticky='WE', columnspan=3) # Add some space around each widget for child in quoteFrame.winfo_children(): child.grid_configure(padx=2, pady=4) #====================================================================================================== # Tab Control 2 #====================================================================================================== # We are creating a container frame to hold all other widgets -- Tab2 self.mySQL2 = ttk.LabelFrame(tab2, text=WIDGET_LABEL) self.mySQL2.grid(column=0, row=0, padx=8, pady=4) # Creating three checkbuttons self.chVarDis = tk.IntVar() self.check1 = tk.Checkbutton(self.mySQL2, text="Disabled", variable=self.chVarDis, state='disabled') self.check1.select() self.check1.grid(column=0, row=0, sticky=tk.W) self.chVarUn = tk.IntVar() self.check2 = tk.Checkbutton(self.mySQL2, text="UnChecked", variable=self.chVarUn) self.check2.deselect() self.check2.grid(column=1, row=0, sticky=tk.W ) self.chVarEn = tk.IntVar() self.check3 = tk.Checkbutton(self.mySQL2, text="Toggle", variable=self.chVarEn) self.check3.deselect() self.check3.grid(column=2, row=0, sticky=tk.W) # trace the state of the two checkbuttons self.chVarUn.trace('w', lambda unused0, unused1, unused2 : self.checkCallback()) self.chVarEn.trace('w', lambda unused0, unused1, unused2 : self.checkCallback()) # Radiobutton list colors = ["Blue", "Gold", "Red"] self.radVar = tk.IntVar() # Selecting a non-existing index value for radVar self.radVar.set(99) # Creating all three Radiobutton widgets within one loop for col in range(3): curRad = 'rad' + str(col) curRad = tk.Radiobutton(self.mySQL2, text=colors[col], variable=self.radVar, value=col, command=self.radCall) curRad.grid(column=col, row=6, sticky=tk.W, columnspan=3) # And now adding tooltips tt.createToolTip(curRad, 'This is a Radiobutton control.') # Create a container to hold labels labelsFrame = ttk.LabelFrame(self.mySQL2, text=' Labels within a Frame ') labelsFrame.grid(column=0, row=7, pady=6) # Place labels into the container element - vertically ttk.Label(labelsFrame, text="Choose a number:").grid(column=0, row=0) ttk.Label(labelsFrame, text="Label 2").grid(column=0, row=1) # Add some space around each label for child in labelsFrame.winfo_children(): child.grid_configure(padx=6, pady=1) number = tk.StringVar() self.combo = ttk.Combobox(self.mySQL2, width=12, textvariable=number) self.combo['values'] = (1, 2, 4, 42, 100) self.combo.grid(column=1, row=7, sticky=tk.W) self.combo.current(0) self.combo.bind('<<ComboboxSelected>>', self._combo) # Adding a Spinbox widget using a set of values self.spin = Spinbox(self.mySQL2, values=(1, 2, 4, 42, 100), width=5, bd=8, command=self._spin) self.spin.grid(column=2, row=7, sticky='W,', padx=6, pady=1) # Using a scrolled Text control scrolW = 40; scrolH = 1 self.scr = scrolledtext.ScrolledText(self.mySQL2, width=scrolW, height=scrolH, wrap=tk.WORD) self.scr.grid(column=0, row=8, sticky='WE', columnspan=3) # Create Manage Files Frame ------------------------------------------------ mngFilesFrame = ttk.LabelFrame(tab2, text=' Manage Files: ') mngFilesFrame.grid(column=0, row=1, sticky='WE', padx=10, pady=5) # Button Callback def getFileName(): print('hello from getFileName') fDir = path.dirname(__file__) fName = fd.askopenfilename(parent=self.win, initialdir=fDir) print(fName) self.fileEntry.config(state='enabled') self.fileEntry.delete(0, tk.END) self.fileEntry.insert(0, fName) if len(fName) > self.entryLen: self.fileEntry.config(width=len(fName) + 3) # Add Widgets to Manage Files Frame lb = ttk.Button(mngFilesFrame, text="Browse to File...", command=getFileName) lb.grid(column=0, row=0, sticky=tk.W) #----------------------------------------------------- file = tk.StringVar() self.entryLen = scrolW - 4 self.fileEntry = ttk.Entry(mngFilesFrame, width=self.entryLen, textvariable=file) self.fileEntry.grid(column=1, row=0, sticky=tk.W) #----------------------------------------------------- logDir = tk.StringVar() self.netwEntry = ttk.Entry(mngFilesFrame, width=self.entryLen, textvariable=logDir) self.netwEntry.grid(column=1, row=1, sticky=tk.W) def copyFile(): import shutil src = self.fileEntry.get() file = src.split('/')[-1] dst = self.netwEntry.get() + '\\'+ file try: shutil.copy(src, dst) mBox.showinfo('Copy File to Network', 'Succes: File copied.') except FileNotFoundError as err: mBox.showerror('Copy File to Network', '*** Failed to copy file! ***\n\n' + str(err)) except Exception as ex: mBox.showerror('Copy File to Network', '*** Failed to copy file! ***\n\n' + str(ex)) cb = ttk.Button(mngFilesFrame, text="Copy File To : ", command=copyFile) cb.grid(column=0, row=1, sticky=tk.E) # Add some space around each label for child in mngFilesFrame.winfo_children(): child.grid_configure(padx=6, pady=6) # Creating a Menu Bar ========================================================== menuBar = Menu(tab1) self.win.config(menu=menuBar) # Add menu items fileMenu = Menu(menuBar, tearoff=0) fileMenu.add_command(label="New") fileMenu.add_separator() fileMenu.add_command(label="Exit", command=self._quit) menuBar.add_cascade(label="File", menu=fileMenu) # Add another Menu to the Menu Bar and an item helpMenu = Menu(menuBar, tearoff=0) helpMenu.add_command(label="About") menuBar.add_cascade(label="Help", menu=helpMenu) # Change the main windows icon self.win.iconbitmap(r'C:\Python34\DLLs\pyc.ico') # Using tkinter Variable Classes strData = tk.StringVar() strData.set('Hello StringVar') # It is not necessary to create a tk.StringVar() strData = tk.StringVar() strData = self.spin.get() # Place cursor into name Entry self.bookTitle.focus() # Add a Tooltip to the Spinbox tt.createToolTip(self.spin, 'This is a Spin control.') # Add Tooltips to more widgets tt.createToolTip(self.bookTitle, 'This is an Entry control.') tt.createToolTip(self.action, 'This is a Button control.') tt.createToolTip(self.scr, 'This is a ScrolledText control.')
# Adding a Textbox Entry widget name = tk.StringVar() nameEntered = ttk.Entry(win, width=10, textvariable=name) nameEntered.grid(column=0, row=1) # Adding a Button action = ttk.Button(win, text="Click Me!", command=clickMe) action.grid(column=2, row=1) # action.configure(state='disabled') # Disable the Button Widget ttk.Label(win, text="Choose a number:").grid(column=1, row=0) number = tk.StringVar() numberChosen = ttk.Combobox(win, width=12, textvariable=number) numberChosen['values'] = ("", 1, 2, 4, 42, 100) numberChosen.grid(column=1, row=1) numberChosen.current("0") # Spinbox callback def _spin(): value = spin.get() print(value) scr.insert(tk.INSERT, value + '\n') # Adding a Spinbox widget spin = Spinbox(win, from_=0, to=10, width=10, bd=6) # bd=border width spin.grid(column=0, row=2) # ====================== win.mainloop()
def create_widgets(self): tabControl = ttk.Notebook(self.win) # Create Tab Control tab1 = ttk.Frame(tabControl) # Create a tab tabControl.add(tab1, text='Tab 1') # Add the tab tab2 = ttk.Frame(tabControl) # Add a second tab tabControl.add(tab2, text='Tab 2') # Make second tab visible tabControl.pack(expand=1, fill="both") # Pack to make visible # LabelFrame using tab1 as the parent mighty = ttk.LabelFrame(tab1, text=' Mighty Python ') mighty.grid(column=0, row=0, padx=8, pady=4) # Modify adding a Label using mighty as the parent instead of win a_label = ttk.Label(mighty, text="Enter a name:") a_label.grid(column=0, row=0, sticky='W') # Adding a Textbox Entry widget self.name = tk.StringVar() self.name_entered = ttk.Entry(mighty, width=12, textvariable=self.name) self.name_entered.grid(column=0, row=1, sticky='W') # Adding a Button self.action = ttk.Button(mighty, text="Click Me!", command=self.click_me) self.action.grid(column=2, row=1) ttk.Label(mighty, text="Choose a number:").grid(column=1, row=0) number = tk.StringVar() self.number_chosen = ttk.Combobox(mighty, width=12, textvariable=number, state='readonly') self.number_chosen['values'] = (1, 2, 4, 42, 100) self.number_chosen.grid(column=1, row=1) self.number_chosen.current(0) # Adding a Spinbox widget self.spin = Spinbox(mighty, values=(1, 2, 4, 42, 100), width=5, bd=9, command=self._spin) # using range self.spin.grid(column=0, row=2) # Using a scrolled Text control scrol_w = 30 scrol_h = 8 self.scrol = scrolledtext.ScrolledText(mighty, width=scrol_w, height=scrol_h, wrap=tk.WORD) self.scrol.grid(column=0, row=3, sticky='WE', columnspan=3) for child in mighty.winfo_children( ): # add spacing to align widgets within tabs child.grid_configure(padx=4, pady=2) #===================================================================================== # Tab Control 2 ---------------------------------------------------------------------- self.mighty2 = ttk.LabelFrame(tab2, text=' The Snake ') self.mighty2.grid(column=0, row=0, padx=8, pady=4) # Creating three checkbuttons chVarDis = tk.IntVar() check1 = tk.Checkbutton(self.mighty2, text="Disabled", variable=chVarDis, state='disabled') check1.select() check1.grid(column=0, row=0, sticky=tk.W) chVarUn = tk.IntVar() check2 = tk.Checkbutton(self.mighty2, text="UnChecked", variable=chVarUn) check2.deselect() check2.grid(column=1, row=0, sticky=tk.W) chVarEn = tk.IntVar() check3 = tk.Checkbutton(self.mighty2, text="Enabled", variable=chVarEn) check3.deselect() check3.grid(column=2, row=0, sticky=tk.W) # trace the state of the two checkbuttons chVarUn.trace('w', lambda unused0, unused1, unused2: self.checkCallback()) chVarEn.trace('w', lambda unused0, unused1, unused2: self.checkCallback()) # First, we change our Radiobutton global variables into a list colors = ["Blue", "Gold", "Red"] # create three Radiobuttons using one variable self.radVar = tk.IntVar() # Next we are selecting a non-existing index value for radVar self.radVar.set(99) # Now we are creating all three Radiobutton widgets within one loop for col in range(3): curRad = tk.Radiobutton(self.mighty2, text=colors[col], variable=self.radVar, value=col, command=self.radCall) curRad.grid(column=col, row=1, sticky=tk.W) # And now adding tooltips ToolTip(curRad, 'This is a Radiobutton control') # Add a Progressbar to Tab 2 self.progress_bar = ttk.Progressbar(tab2, orient='horizontal', length=286, mode='determinate') self.progress_bar.grid(column=0, row=3, pady=2) # Create a container to hold buttons buttons_frame = ttk.LabelFrame(self.mighty2, text=' ProgressBar ') buttons_frame.grid(column=0, row=2, sticky='W', columnspan=2) # Add Buttons for Progressbar commands ttk.Button(buttons_frame, text=" Run Progressbar ", command=self.run_progressbar).grid(column=0, row=0, sticky='W') ttk.Button(buttons_frame, text=" Start Progressbar ", command=self.start_progressbar).grid(column=0, row=1, sticky='W') ttk.Button(buttons_frame, text=" Stop immediately ", command=self.stop_progressbar).grid(column=0, row=2, sticky='W') ttk.Button(buttons_frame, text=" Stop after second ", command=self.progressbar_stop_after).grid(column=0, row=3, sticky='W') for child in buttons_frame.winfo_children(): child.grid_configure(padx=2, pady=2) for child in self.mighty2.winfo_children(): child.grid_configure(padx=8, pady=2) # Creating a Menu Bar menu_bar = Menu(self.win) self.win.config(menu=menu_bar) # Add menu items file_menu = Menu(menu_bar, tearoff=0) file_menu.add_command(label="New") file_menu.add_separator() file_menu.add_command(label="Exit", command=self._quit) menu_bar.add_cascade(label="File", menu=file_menu) # Display a Message Box def _msgBox(): msg.showinfo( 'Python Message Info Box', 'A Python GUI created using tkinter:\nThe year is 2019.') # Add another Menu to the Menu Bar and an item help_menu = Menu(menu_bar, tearoff=0) help_menu.add_command( label="About", command=_msgBox) # display messagebox when clicked menu_bar.add_cascade(label="Help", menu=help_menu) # Change the main windows icon self.win.iconbitmap('pyc.ico') # It is not necessary to create a tk.StringVar() # strData = tk.StringVar() strData = self.spin.get() print("Spinbox value: " + strData) # call function self.usingGlobal() self.name_entered.focus() # Add Tooltips ----------------------------------------------------- # Add a Tooltip to the Spinbox ToolTip(self.spin, 'This is a Spinbox control') # Add Tooltips to more widgets ToolTip(self.name_entered, 'This is an Entry control') ToolTip(self.action, 'This is a Button control') ToolTip(self.scrol, 'This is a ScrolledText control')
class HVPS: def __init__(self, master): self.master = master master.title("LoCoLab HVPS Console") self.ser = None LCOL = 0 RCOL = 4 # Critical parameters #self.CURRENTVOLTAGE = IntVar(master,value=0) #self.TARGETVOLTAGE = IntVar(master,value=0) #self.PWM = IntVar(master,value=0) self.CURRENTVOLTAGE = StringVar(master, value='0') self.TARGETVOLTAGE = StringVar(master, value='0') self.PWM = StringVar(master, value='30') self.IS_SERIAL_CONNECTED = False # Plotting parameters self.npoints = 240 self.current_line = [0 for x in range(self.npoints)] self.target_line = [0 for x in range(self.npoints)] # Plots =============================================================== self.f1 = plt.figure(figsize=PLOTRATIO, dpi=PLOTDPI) self.a1 = self.f1.add_subplot(111) self.a1.grid() self.a1.set_title("Voltage") self.canvas1 = FigureCanvasTkAgg(self.f1, master) self.canvas1.get_tk_widget().grid(sticky='W', row=0, rowspan=5, column=LCOL + 0, columnspan=RCOL) self.f2 = plt.figure(figsize=PLOTRATIO, dpi=PLOTDPI) self.a2 = self.f2.add_subplot(111) self.a2.grid() self.a2.set_title("PWM") self.canvas2 = FigureCanvasTkAgg(self.f2, master) self.canvas2.get_tk_widget().grid(sticky='W', row=6, rowspan=1, column=LCOL + 0, columnspan=RCOL) self.f3 = plt.figure(figsize=PLOTRATIO, dpi=PLOTDPI) self.a3 = self.f3.add_subplot(111) self.a3.grid() self.a3.set_title("Signal") self.canvas3 = FigureCanvasTkAgg(self.f3, master) self.canvas3.get_tk_widget().grid(sticky='W', row=6, rowspan=1, column=RCOL + 1, columnspan=7) self.a3_xlim = 0 self.a3_ylim = 0 # Labels ============================================================== self.currentlabel = Label(master, text="Current:", font=LABELFONT) self.currentlabel.grid(row=0, column=RCOL + 1) self.dynamic_currentlabel = Label(master, textvar=self.CURRENTVOLTAGE, font=LABELFONT) self.dynamic_currentlabel.grid(row=0, column=RCOL + 2, sticky='W') self.currentunitslabel = Label(master, text="kV") self.currentunitslabel.grid(row=0, column=RCOL + 3, sticky='W') self.targetlabel = Label(master, text="Target:", font=LABELFONT) self.targetlabel.grid(row=1, column=RCOL + 1) self.dynamic_targetlabel = Label(master, textvar=self.TARGETVOLTAGE, font=LABELFONT) self.dynamic_targetlabel.grid(row=1, column=RCOL + 2, sticky='W') self.targetunitslabel = Label(master, text="kV") self.targetunitslabel.grid(row=1, column=RCOL + 3, sticky='W') self.pwmlabel = Label(master, text="PWM:", font=LABELFONT) self.pwmlabel.grid(row=2, column=RCOL + 1) self.dynamic_pwmlabel = Label(master, textvar=self.PWM, font=LABELFONT) self.dynamic_pwmlabel.grid(row=2, column=RCOL + 2, sticky='W') self.pwmunitslabel = Label(master, text="/ 1023") self.pwmunitslabel.grid(row=2, column=RCOL + 3, sticky='W') # Target Voltage Input ================================================ self.targetvoltageentrystr = StringVar(master, value='0') self.targetvoltageentry = Entry(master, textvar=self.targetvoltageentrystr) self.targetvoltageentry.grid(row=1, column=RCOL + 4) self.targetvoltagesendbutton = Button(master, text="Send", command=self.SendVoltage) self.targetvoltagesendbutton.grid(row=1, column=RCOL + 5) # Signal ============================================================== # self.signallabel = Label(master,text="Signal:") # self.signallabel.grid(row=3,column=1) self.IS_SENDING_SIGNAL = False self.signalx = [] self.signaly = [] self.signallistbox = Listbox(master, height=2) self.signallistbox.insert(1, "Step") self.signallistbox.insert(2, "Stairstep") self.signallistbox.insert(3, "Sawtooth") self.signallistbox.grid(sticky='E', row=7, column=RCOL + 1, columnspan=2) self.amplitudelabel = Label(master, text="Amplitude:") self.amplitudelabel.grid(row=8, column=RCOL + 1) self.amplitudeentrystr = StringVar(master, value='0.5') self.amplitudeentry = Entry(master, textvar=self.amplitudeentrystr) self.amplitudeentry.grid(row=8, column=RCOL + 2, columnspan=2) self.amplitudeunitslabel = Label(master, text="kV") self.amplitudeunitslabel.grid(row=8, column=RCOL + 4) self.dwelltimelabel = Label(master, text="Dwell time:") self.dwelltimelabel.grid(row=9, column=RCOL + 1) self.dwelltimeentrystr = StringVar(master, value='30') self.dwelltimeentry = Entry(master, textvar=self.dwelltimeentrystr) self.dwelltimeentry.grid(row=9, column=RCOL + 2, columnspan=2) self.dwelltimeunitslabel = Label(master, text="sec") self.dwelltimeunitslabel.grid(row=9, column=RCOL + 4) self.nrepslabel = Label(master, text="# Reps:") self.nrepslabel.grid(row=10, column=RCOL + 1) self.nrepsspinbox = Spinbox(master, from_=0, to_=50) self.nrepsspinbox.grid(row=10, column=RCOL + 2, columnspan=2) self.updatesignalbutton = Button(master, text="Update", command=self.UpdateSignalButton) self.updatesignalbutton.grid(row=11, column=RCOL + 1) self.executesignalbutton = Button(master, text="Execute", command=self.ExecuteSignalButton) self.executesignalbutton.grid(row=11, column=RCOL + 2) # Serial port ========================================================= self.seriallabel = Label(master, text="Serial Port") self.seriallabel.grid(sticky='W', row=7, column=0) self.serialentrystr = StringVar(master, value='/dev/cu.wchusbserial1420') self.serialentry = Entry(master, textvar=self.serialentrystr) self.serialentry.grid(sticky='W', row=7, column=1) self.serialconnectbutton = Button(master, text="Connect", command=self.ConnectToSerial) self.serialconnectbutton.grid(sticky='W', row=7, column=2) self.baudratelabel = Label(master, text="Baud Rate") self.baudratelabel.grid(sticky='W', row=8, column=0) self.baudrateentrystr = StringVar(master, value='115200') self.baudrateentry = Entry(master, textvar=self.baudrateentrystr) self.baudrateentry.grid(sticky='W', row=8, column=1) # Data Logging ======================================================== self.loglabel = Label(master, text="Data Logging") self.loglabel.grid(sticky='W', row=9, column=0) self.logfnameentrystr = StringVar(master, value='SessionLog.txt') self.logfnameentry = Entry(master, textvar=self.logfnameentrystr) self.logfnameentry.grid(sticky='W', row=9, column=1) self.logging_variable = IntVar(master, value=0) self.logging_offbutton = Radiobutton(master, text="Off", variable=self.logging_variable, value=0, width=4) self.logging_offbutton.grid(row=9, column=2) self.logging_onbutton = Radiobutton(master, text="On", variable=self.logging_variable, value=1, width=4) self.logging_onbutton.grid(row=9, column=3) # Abort =============================================================== self.abortbutton = Button(master, text="ABORT", command=self.ABORT) self.abortbutton.grid(row=11, column=0) return def DoNothing(self): pass def SendVoltage(self, sendv=0): try: V = float(self.targetvoltageentrystr.get()) if sendv != 0: V = sendv self.TARGETVOLTAGE.set(str(V)) w_str = "%f\n" % (V) # Format to send voltage self.ser.write(w_str.encode()) except Exception as e: print("ERROR: %s" % (e)) return def ConnectToSerial(self): try: port = self.serialentrystr.get() baudrate = int(self.baudrateentrystr.get()) print("Trying to connect to %s at %d" % (port, baudrate)) self.ser = serial.Serial(port, baudrate) self.ser.flushInput() except ValueError: print("ERROR: Invalid serial parameter.") return -1 except: print("Error") return -1 print("Success.") self.IS_SERIAL_CONNECTED = True self.GetSerialValue() return def GetSerialValue(self): if not self.IS_SERIAL_CONNECTED: #self.master.after(50,self.GetSerialValue) return try: # Grab data rawdata = self.ser.readline().decode('utf8') # Parse data currentval = float(rawdata.split(' ')[0]) targetval = float(self.TARGETVOLTAGE.get()) self.CURRENTVOLTAGE.set(str(currentval)) if self.logging_variable.get() == 1: self.LogData([targetval, currentval]) # Append data, shift over lines self.current_line.append(currentval) self.current_line = self.current_line[1:self.npoints + 1] self.target_line.append(targetval) self.target_line = self.target_line[1:self.npoints + 1] if self.IS_SENDING_SIGNAL: if len(self.signaly) == 0: self.IS_SENDING_SIGNAL = False else: #print("Sending signal: %f, next is "%(self.signaly[0]),end="") #self.SendVoltage(self.signaly[0]) v = self.signaly[0] self.TARGETVOLTAGE.set("%f" % (v)) wstr = "%f\n" % (v) self.ser.write(wstr.encode()) self.signaly = self.signaly[1:] self.signalx = self.signalx[:-1] #print("%f"%(self.signaly[0])) self.a3.clear() self.a3.plot(self.signalx, self.signaly, color='tab:blue') self.a3.set_title("Signal") self.a3.set_xlim(0, self.a3_xlim) self.a3.set_ylim(0, self.a3_ylim) self.a3.grid() self.canvas3.draw() self.master.after_idle(self.PlotLine) except Exception as e: print(e) self.master.after(REFRESH_FREQ, self.GetSerialValue) return def PlotLine(self): #max_val = max(self.current_line) + 1e-5 # Include extra for padding? self.a1.clear() self.a1.plot(self.current_line, color='tab:blue', label='Actual') self.a1.plot(self.target_line, color='tab:green', linestyle=':', label='Target') self.a1.grid() self.a1.legend(loc=3) self.a1.set_ylim(-1.5, 1.5) self.canvas1.draw() #print("Beep") return def UpdateSignalButton(self): try: selected_signal = self.signallistbox.curselection()[0] except: print("No selection!") return #print(selected_signal) try: H = float(self.amplitudeentrystr.get()) W = float(self.dwelltimeentrystr.get()) n = int(self.nrepsspinbox.get()) except ValueError: print("ERROR: Invalid signal parameter.") return if selected_signal == 0: # Step case self.signalx, self.signaly = Step(H, W, n) elif selected_signal == 1: self.signalx, self.signaly = StairStep(H, W, n) elif selected_signal == 2: self.signalx, self.signaly = Sawtooth(H, W, n) # Plot to a3 self.a3_xlim = max(self.signalx) self.a3_ylim = max(self.signaly) * 1.2 self.a3.clear() self.a3.plot(self.signalx, self.signaly, color='tab:blue') self.a3.set_title("Signal") self.a3.set_xlim(0, self.a3_xlim) self.a3.set_ylim(0, self.a3_ylim) self.a3.grid() self.canvas3.draw() return def ExecuteSignalButton(self): self.IS_SENDING_SIGNAL = True self.targetvoltagesendbutton.state = DISABLED print("Beep") return def mainloop(self): self.master.mainloop() return def LogData(self, data): fname = self.logfnameentrystr.get() f = open(fname, 'a') writestr = '' for d in data: writestr += "%f," % (d) writestr = writestr[:-1] + '\n' f.write(writestr) f.close() return def OnUpdate(self): pass def OnExecute(self): pass def ABORT(self): self.IS_SERIAL_CONNECTED = False self.TARGETVOLTAGE.set('0') self.IS_SENDING_SIGNAL = False self.signalx = [] self.signaly = [] return
def guiMain(settings=None): frames = {} mainWindow = Tk() mainWindow.wm_title("OoT Randomizer %s" % ESVersion) mainWindow.resizable(False, False) set_icon(mainWindow) notebook = ttk.Notebook(mainWindow) frames['rom_tab'] = ttk.Frame(notebook) frames['rules_tab'] = ttk.Frame(notebook) frames['logic_tab'] = ttk.Frame(notebook) frames['other_tab'] = ttk.Frame(notebook) frames['aesthetic_tab'] = ttk.Frame(notebook) frames['aesthetic_tab_left'] = Frame(frames['aesthetic_tab']) frames['aesthetic_tab_right'] = Frame(frames['aesthetic_tab']) adjustWindow = ttk.Frame(notebook) customWindow = ttk.Frame(notebook) notebook.add(frames['rom_tab'], text='ROM Options') notebook.add(frames['rules_tab'], text='Main Rules') notebook.add(frames['logic_tab'], text='Detailed Logic') notebook.add(frames['other_tab'], text='Other') notebook.add(frames['aesthetic_tab'], text='Cosmetics') ####################### # randomizer controls # ####################### # hold the results of the user's decisions here guivars = {} # hierarchy ############ #Rules Tab frames['open'] = LabelFrame(frames['rules_tab'], text='Open', labelanchor=NW) frames['world'] = LabelFrame(frames['rules_tab'], text='World', labelanchor=NW) frames['logic'] = LabelFrame(frames['rules_tab'], text='Shuffle', labelanchor=NW) # Logic tab frames['rewards'] = LabelFrame(frames['logic_tab'], text='Remove Specific Locations', labelanchor=NW) frames['tricks'] = LabelFrame(frames['logic_tab'], text='Specific expected tricks', labelanchor=NW) #Other Tab frames['convenience'] = LabelFrame(frames['other_tab'], text='Speed Ups', labelanchor=NW) frames['other'] = LabelFrame(frames['other_tab'], text='Misc', labelanchor=NW) #Aesthetics tab frames['cosmetics'] = LabelFrame(frames['aesthetic_tab'], text='General', labelanchor=NW) frames['tuniccolor'] = LabelFrame(frames['aesthetic_tab_left'], text='Tunic Color', labelanchor=NW) frames['navicolor'] = LabelFrame(frames['aesthetic_tab_right'], text='Navi Color', labelanchor=NW) frames['lowhp'] = LabelFrame(frames['aesthetic_tab_left'], text='Low HP SFX', labelanchor=NW) frames['navihint'] = LabelFrame(frames['aesthetic_tab_right'], text='Navi SFX', labelanchor=NW) # shared settingsFrame = Frame(mainWindow) settings_string_var = StringVar() settingsEntry = Entry(settingsFrame, textvariable=settings_string_var, width=25) def show_settings(event=None): settings = guivars_to_settings(guivars) settings_string_var.set(settings.get_settings_string()) # Update any dependencies for info in setting_infos: if info.gui_params and 'dependency' in info.gui_params: dep_met = info.gui_params['dependency'](guivars) if widgets[info.name].winfo_class() == 'Frame': for child in widgets[info.name].winfo_children(): if child.winfo_class() == 'TCombobox': child.configure( state='readonly' if dep_met else 'disabled') else: child.configure( state='normal' if dep_met else 'disabled') if child.winfo_class() == 'Scale': child.configure(fg='Black' if dep_met else 'Grey') else: if widgets[info.name].winfo_class() == 'TCombobox': widgets[info.name].configure( state='readonly' if dep_met else 'disabled') else: widgets[info.name].configure( state='normal' if dep_met else 'disabled') if widgets[info.name].winfo_class() == 'Scale': widgets[info.name].configure( fg='Black' if dep_met else 'Grey') if info.name in guivars and guivars[ info.name].get() == 'Custom Color': color = askcolor() if color == (None, None): color = ((0, 0, 0), '#000000') guivars[info.name].set('Custom (' + color[1] + ')') def show_settings_special(event=None): if guivars['logic_tricks'].get(): widgets['logic_man_on_roof'].select() widgets['logic_child_deadhand'].select() widgets['logic_dc_jump'].select() widgets['logic_windmill_poh'].select() widgets['logic_crater_bean_poh_with_hovers'].select() widgets['logic_zora_with_cucco'].select() widgets['logic_fewer_tunic_requirements'].select() else: widgets['logic_man_on_roof'].deselect() widgets['logic_child_deadhand'].deselect() widgets['logic_dc_jump'].deselect() widgets['logic_windmill_poh'].deselect() widgets['logic_crater_bean_poh_with_hovers'].deselect() widgets['logic_zora_with_cucco'].deselect() widgets['logic_fewer_tunic_requirements'].deselect() settings = guivars_to_settings(guivars) settings_string_var.set(settings.get_settings_string()) def import_settings(event=None): try: settings = guivars_to_settings(guivars) text = settings_string_var.get().upper() settings.seed = guivars['seed'].get() settings.update_with_settings_string(text) settings_to_guivars(settings, guivars) except Exception as e: messagebox.showerror(title="Error", message="Invalid settings string") label = Label(settingsFrame, text="Settings String") importSettingsButton = Button(settingsFrame, text='Import Settings String', command=import_settings) label.pack(side=LEFT, anchor=W, padx=5) settingsEntry.pack(side=LEFT, anchor=W) importSettingsButton.pack(side=LEFT, anchor=W, padx=5) fileDialogFrame = Frame(frames['rom_tab']) romDialogFrame = Frame(fileDialogFrame) baseRomLabel = Label(romDialogFrame, text='Base ROM') guivars['rom'] = StringVar(value='ZOOTDEC.z64') romEntry = Entry(romDialogFrame, textvariable=guivars['rom'], width=40) def RomSelect(): rom = filedialog.askopenfilename( filetypes=[("ROM Files", (".z64", ".n64")), ("All Files", "*")]) if rom != '': guivars['rom'].set(rom) romSelectButton = Button(romDialogFrame, text='Select ROM', command=RomSelect, width=10) baseRomLabel.pack(side=LEFT, padx=(38, 0)) romEntry.pack(side=LEFT, padx=3) romSelectButton.pack(side=LEFT) romDialogFrame.pack() fileDialogFrame.pack(side=TOP, anchor=W, padx=5, pady=(5, 1)) def open_output(): open_file(output_path('')) def output_dir_select(): rom = filedialog.askdirectory( initialdir=default_output_path(guivars['output_dir'].get())) if rom != '': guivars['output_dir'].set(rom) outputDialogFrame = Frame(frames['rom_tab']) outputDirLabel = Label(outputDialogFrame, text='Output Directory') guivars['output_dir'] = StringVar(value='') outputDirEntry = Entry(outputDialogFrame, textvariable=guivars['output_dir'], width=40) outputDirButton = Button(outputDialogFrame, text='Select Dir', command=output_dir_select, width=10) outputDirLabel.pack(side=LEFT, padx=(3, 0)) outputDirEntry.pack(side=LEFT, padx=3) outputDirButton.pack(side=LEFT) outputDialogFrame.pack(side=TOP, anchor=W, padx=5, pady=(5, 1)) if os.path.exists(local_path('README.html')): def open_readme(): open_file(local_path('README.html')) openReadmeButton = Button(outputDialogFrame, text='Open Documentation', command=open_readme) openReadmeButton.pack(side=LEFT, padx=5) outputDialogFrame.pack(side=TOP, anchor=W, pady=3) countDialogFrame = Frame(frames['rom_tab']) countLabel = Label(countDialogFrame, text='Generation Count') guivars['count'] = StringVar() countSpinbox = Spinbox(countDialogFrame, from_=1, to=100, textvariable=guivars['count'], width=3) countLabel.pack(side=LEFT) countSpinbox.pack(side=LEFT, padx=2) countDialogFrame.pack(side=TOP, anchor=W, padx=5, pady=(1, 1)) # build gui ############ widgets = {} for info in setting_infos: if info.gui_params: if info.gui_params['widget'] == 'Checkbutton': # determine the initial value of the checkbox default_value = 1 if info.gui_params[ 'default'] == "checked" else 0 # create a variable to access the box's state guivars[info.name] = IntVar(value=default_value) # create the checkbox widgets[info.name] = Checkbutton( frames[info.gui_params['group']], text=info.gui_params['text'], variable=guivars[info.name], justify=LEFT, wraplength=190, command=show_settings) widgets[info.name].pack(expand=False, anchor=W) if info.gui_params['widget'] == 'SpecialCheckbutton': # determine the initial value of the checkbox default_value = 1 if info.gui_params[ 'default'] == "checked" else 0 # create a variable to access the box's state guivars[info.name] = IntVar(value=default_value) # create the checkbox widgets[info.name] = Checkbutton( frames[info.gui_params['group']], text=info.gui_params['text'], variable=guivars[info.name], justify=LEFT, wraplength=190, command=show_settings_special) widgets[info.name].pack(expand=False, anchor=W) elif info.gui_params['widget'] == 'Combobox': # create the variable to store the user's decision guivars[info.name] = StringVar( value=info.gui_params['default']) # create the option menu widgets[info.name] = Frame(frames[info.gui_params['group']]) # dropdown = OptionMenu(widgets[info.name], guivars[info.name], *(info['options'])) if isinstance(info.gui_params['options'], list): info.gui_params['options'] = dict( zip(info.gui_params['options'], info.gui_params['options'])) dropdown = ttk.Combobox(widgets[info.name], textvariable=guivars[info.name], values=list( info.gui_params['options'].keys()), state='readonly', width=30) dropdown.bind("<<ComboboxSelected>>", show_settings) dropdown.pack(side=BOTTOM, anchor=W) # label the option if 'text' in info.gui_params: label = Label(widgets[info.name], text=info.gui_params['text']) label.pack(side=LEFT, anchor=W, padx=5) # pack the frame widgets[info.name].pack(expand=False, side=TOP, anchor=W, padx=3, pady=3) elif info.gui_params['widget'] == 'Radiobutton': # create the variable to store the user's decision guivars[info.name] = StringVar( value=info.gui_params['default']) # create the option menu widgets[info.name] = LabelFrame( frames[info.gui_params['group']], text=info.gui_params['text'] if 'text' in info.gui_params else info["name"], labelanchor=NW) if isinstance(info.gui_params['options'], list): info.gui_params['options'] = dict( zip(info.gui_params['options'], info.gui_params['options'])) # setup orientation side = TOP anchor = W if "horizontal" in info.gui_params and info.gui_params[ "horizontal"]: side = LEFT anchor = N # add the radio buttons for option in info.gui_params["options"]: radio_button = Radiobutton(widgets[info.name], text=option, value=option, variable=guivars[info.name], justify=LEFT, wraplength=190, indicatoron=False, command=show_settings) radio_button.pack(expand=True, side=side, anchor=anchor) # pack the frame widgets[info.name].pack(expand=False, side=TOP, anchor=W, padx=3, pady=3) elif info.gui_params['widget'] == 'Scale': # create the variable to store the user's decision guivars[info.name] = IntVar(value=info.gui_params['default']) # create the option menu widgets[info.name] = Frame(frames[info.gui_params['group']]) # dropdown = OptionMenu(widgets[info.name], guivars[info.name], *(info['options'])) minval = 'min' in info.gui_params and info.gui_params[ 'min'] or 0 maxval = 'max' in info.gui_params and info.gui_params[ 'max'] or 100 stepval = 'step' in info.gui_params and info.gui_params[ 'step'] or 1 scale = Scale(widgets[info.name], variable=guivars[info.name], from_=minval, to=maxval, tickinterval=stepval, resolution=stepval, showvalue=0, orient=HORIZONTAL, sliderlength=15, length=200, command=show_settings) scale.pack(side=BOTTOM, anchor=W) # label the option if 'text' in info.gui_params: label = Label(widgets[info.name], text=info.gui_params['text']) label.pack(side=LEFT, anchor=W, padx=5) # pack the frame widgets[info.name].pack(expand=False, side=TOP, anchor=W, padx=3, pady=3) elif info.gui_params['widget'] == 'Entry': # create the variable to store the user's decision guivars[info.name] = StringVar( value=info.gui_params['default']) # create the option menu widgets[info.name] = Frame(frames[info.gui_params['group']]) entry = Entry(widgets[info.name], textvariable=guivars[info.name], width=30) entry.pack(side=BOTTOM, anchor=W) # label the option if 'text' in info.gui_params: label = Label(widgets[info.name], text=info.gui_params['text']) label.pack(side=LEFT, anchor=W, padx=5) # pack the frame widgets[info.name].pack(expand=False, side=TOP, anchor=W, padx=3, pady=3) if 'tooltip' in info.gui_params: ToolTips.register(widgets[info.name], info.gui_params['tooltip']) # pack the hierarchy frames['logic'].pack(fill=BOTH, expand=True, anchor=N, side=RIGHT, pady=(5, 1)) frames['open'].pack(fill=BOTH, expand=True, anchor=W, side=TOP, pady=(5, 1)) frames['world'].pack(fill=BOTH, expand=True, anchor=W, side=BOTTOM, pady=(5, 1)) # Logic tab frames['rewards'].pack(fill=BOTH, expand=True, anchor=N, side=LEFT, pady=(5, 1)) frames['tricks'].pack(fill=BOTH, expand=True, anchor=N, side=LEFT, pady=(5, 1)) #Other Tab frames['convenience'].pack(fill=BOTH, expand=True, anchor=N, side=LEFT, pady=(5, 1)) frames['other'].pack(fill=BOTH, expand=True, anchor=N, side=LEFT, pady=(5, 1)) #Aesthetics tab frames['cosmetics'].pack(fill=BOTH, expand=True, anchor=W, side=TOP) frames['aesthetic_tab_left'].pack(fill=BOTH, expand=True, anchor=W, side=LEFT) frames['aesthetic_tab_right'].pack(fill=BOTH, expand=True, anchor=W, side=RIGHT) #Aesthetics tab - Left Side frames['tuniccolor'].pack(fill=BOTH, expand=True, anchor=W, side=TOP, pady=(5, 1)) frames['lowhp'].pack(fill=BOTH, expand=True, anchor=W, side=TOP, pady=(5, 1)) #Aesthetics tab - Right Side frames['navicolor'].pack(fill=BOTH, expand=True, anchor=W, side=TOP, pady=(5, 1)) frames['navihint'].pack(fill=BOTH, expand=True, anchor=W, side=TOP, pady=(5, 1)) notebook.pack(fill=BOTH, expand=True, padx=5, pady=5) multiworldFrame = LabelFrame(frames['rom_tab'], text='Multi-World Generation') countLabel = Label( multiworldFrame, wraplength=350, justify=LEFT, text= 'This is used for co-op generations. Increasing Player Count will drastically increase the generation time. For more information see:' ) hyperLabel = Label(multiworldFrame, wraplength=350, justify=LEFT, text='https://github.com/TestRunnerSRL/bizhawk-co-op', fg='blue', cursor='hand2') hyperLabel.bind( "<Button-1>", lambda event: webbrowser.open_new( r"https://github.com/TestRunnerSRL/bizhawk-co-op")) countLabel.pack(side=TOP, anchor=W, padx=5, pady=0) hyperLabel.pack(side=TOP, anchor=W, padx=5, pady=0) worldCountFrame = Frame(multiworldFrame) countLabel = Label(worldCountFrame, text='Player Count') guivars['world_count'] = StringVar() countSpinbox = Spinbox(worldCountFrame, from_=1, to=100, textvariable=guivars['world_count'], width=3) countLabel.pack(side=LEFT) countSpinbox.pack(side=LEFT, padx=2) worldCountFrame.pack(side=LEFT, anchor=N, padx=10, pady=(1, 5)) playerNumFrame = Frame(multiworldFrame) countLabel = Label(playerNumFrame, text='Player ID') guivars['player_num'] = StringVar() countSpinbox = Spinbox(playerNumFrame, from_=1, to=100, textvariable=guivars['player_num'], width=3) countLabel.pack(side=LEFT) countSpinbox.pack(side=LEFT, padx=2) playerNumFrame.pack(side=LEFT, anchor=N, padx=10, pady=(1, 5)) multiworldFrame.pack(side=TOP, anchor=W, padx=5, pady=(1, 1)) # didn't refactor the rest, sorry # create the option menu settingsFrame.pack(fill=BOTH, anchor=W, padx=5, pady=(10, 0)) def multiple_run(settings, window): orig_seed = settings.seed for i in range(settings.count): settings.update_seed(orig_seed + '-' + str(i)) window.update_title("Generating Seed...%d/%d" % (i + 1, settings.count)) main(settings, window) def generateRom(): settings = guivars_to_settings(guivars) if settings.count is not None: BackgroundTaskProgress(mainWindow, "Generating Seed...", multiple_run, settings) else: BackgroundTaskProgress(mainWindow, "Generating Seed...", main, settings) generateSeedFrame = Frame(mainWindow) generateButton = Button(generateSeedFrame, text='Generate Patched Rom', command=generateRom) seedLabel = Label(generateSeedFrame, text='Seed') guivars['seed'] = StringVar() seedEntry = Entry(generateSeedFrame, textvariable=guivars['seed'], width=25) seedLabel.pack(side=LEFT, padx=(55, 5)) seedEntry.pack(side=LEFT) generateButton.pack(side=LEFT, padx=(5, 0)) generateSeedFrame.pack(side=BOTTOM, anchor=W, padx=5, pady=10) guivars['checked_version'] = StringVar() if settings is not None: # load values from commandline args settings_to_guivars(settings, guivars) else: # try to load saved settings try: settingsFile = os.path.join( os.path.dirname(os.path.abspath(__file__)), 'settings.sav') with open(settingsFile) as f: settings = Settings(json.load(f)) settings.update_seed("") settings_to_guivars(settings, guivars) except: pass show_settings() def gui_check_version(): task = BackgroundTask(mainWindow, check_version, guivars['checked_version'].get()) while task.running: mainWindow.update() if task.status: dialog = Dialog(mainWindow, title="Version Error", question=task.status, oktext='Don\'t show again', canceltext='OK') if dialog.result: guivars['checked_version'].set(ESVersion) mainWindow.after(1000, gui_check_version) mainWindow.mainloop() # save settings on close with open('settings.sav', 'w') as outfile: settings = guivars_to_settings(guivars) json.dump(settings.__dict__, outfile)
def __init__(self, master): self.master = master master.title("LoCoLab HVPS Console") self.ser = None LCOL = 0 RCOL = 4 # Critical parameters #self.CURRENTVOLTAGE = IntVar(master,value=0) #self.TARGETVOLTAGE = IntVar(master,value=0) #self.PWM = IntVar(master,value=0) self.CURRENTVOLTAGE = StringVar(master, value='0') self.TARGETVOLTAGE = StringVar(master, value='0') self.PWM = StringVar(master, value='30') self.IS_SERIAL_CONNECTED = False # Plotting parameters self.npoints = 240 self.current_line = [0 for x in range(self.npoints)] self.target_line = [0 for x in range(self.npoints)] # Plots =============================================================== self.f1 = plt.figure(figsize=PLOTRATIO, dpi=PLOTDPI) self.a1 = self.f1.add_subplot(111) self.a1.grid() self.a1.set_title("Voltage") self.canvas1 = FigureCanvasTkAgg(self.f1, master) self.canvas1.get_tk_widget().grid(sticky='W', row=0, rowspan=5, column=LCOL + 0, columnspan=RCOL) self.f2 = plt.figure(figsize=PLOTRATIO, dpi=PLOTDPI) self.a2 = self.f2.add_subplot(111) self.a2.grid() self.a2.set_title("PWM") self.canvas2 = FigureCanvasTkAgg(self.f2, master) self.canvas2.get_tk_widget().grid(sticky='W', row=6, rowspan=1, column=LCOL + 0, columnspan=RCOL) self.f3 = plt.figure(figsize=PLOTRATIO, dpi=PLOTDPI) self.a3 = self.f3.add_subplot(111) self.a3.grid() self.a3.set_title("Signal") self.canvas3 = FigureCanvasTkAgg(self.f3, master) self.canvas3.get_tk_widget().grid(sticky='W', row=6, rowspan=1, column=RCOL + 1, columnspan=7) self.a3_xlim = 0 self.a3_ylim = 0 # Labels ============================================================== self.currentlabel = Label(master, text="Current:", font=LABELFONT) self.currentlabel.grid(row=0, column=RCOL + 1) self.dynamic_currentlabel = Label(master, textvar=self.CURRENTVOLTAGE, font=LABELFONT) self.dynamic_currentlabel.grid(row=0, column=RCOL + 2, sticky='W') self.currentunitslabel = Label(master, text="kV") self.currentunitslabel.grid(row=0, column=RCOL + 3, sticky='W') self.targetlabel = Label(master, text="Target:", font=LABELFONT) self.targetlabel.grid(row=1, column=RCOL + 1) self.dynamic_targetlabel = Label(master, textvar=self.TARGETVOLTAGE, font=LABELFONT) self.dynamic_targetlabel.grid(row=1, column=RCOL + 2, sticky='W') self.targetunitslabel = Label(master, text="kV") self.targetunitslabel.grid(row=1, column=RCOL + 3, sticky='W') self.pwmlabel = Label(master, text="PWM:", font=LABELFONT) self.pwmlabel.grid(row=2, column=RCOL + 1) self.dynamic_pwmlabel = Label(master, textvar=self.PWM, font=LABELFONT) self.dynamic_pwmlabel.grid(row=2, column=RCOL + 2, sticky='W') self.pwmunitslabel = Label(master, text="/ 1023") self.pwmunitslabel.grid(row=2, column=RCOL + 3, sticky='W') # Target Voltage Input ================================================ self.targetvoltageentrystr = StringVar(master, value='0') self.targetvoltageentry = Entry(master, textvar=self.targetvoltageentrystr) self.targetvoltageentry.grid(row=1, column=RCOL + 4) self.targetvoltagesendbutton = Button(master, text="Send", command=self.SendVoltage) self.targetvoltagesendbutton.grid(row=1, column=RCOL + 5) # Signal ============================================================== # self.signallabel = Label(master,text="Signal:") # self.signallabel.grid(row=3,column=1) self.IS_SENDING_SIGNAL = False self.signalx = [] self.signaly = [] self.signallistbox = Listbox(master, height=2) self.signallistbox.insert(1, "Step") self.signallistbox.insert(2, "Stairstep") self.signallistbox.insert(3, "Sawtooth") self.signallistbox.grid(sticky='E', row=7, column=RCOL + 1, columnspan=2) self.amplitudelabel = Label(master, text="Amplitude:") self.amplitudelabel.grid(row=8, column=RCOL + 1) self.amplitudeentrystr = StringVar(master, value='0.5') self.amplitudeentry = Entry(master, textvar=self.amplitudeentrystr) self.amplitudeentry.grid(row=8, column=RCOL + 2, columnspan=2) self.amplitudeunitslabel = Label(master, text="kV") self.amplitudeunitslabel.grid(row=8, column=RCOL + 4) self.dwelltimelabel = Label(master, text="Dwell time:") self.dwelltimelabel.grid(row=9, column=RCOL + 1) self.dwelltimeentrystr = StringVar(master, value='30') self.dwelltimeentry = Entry(master, textvar=self.dwelltimeentrystr) self.dwelltimeentry.grid(row=9, column=RCOL + 2, columnspan=2) self.dwelltimeunitslabel = Label(master, text="sec") self.dwelltimeunitslabel.grid(row=9, column=RCOL + 4) self.nrepslabel = Label(master, text="# Reps:") self.nrepslabel.grid(row=10, column=RCOL + 1) self.nrepsspinbox = Spinbox(master, from_=0, to_=50) self.nrepsspinbox.grid(row=10, column=RCOL + 2, columnspan=2) self.updatesignalbutton = Button(master, text="Update", command=self.UpdateSignalButton) self.updatesignalbutton.grid(row=11, column=RCOL + 1) self.executesignalbutton = Button(master, text="Execute", command=self.ExecuteSignalButton) self.executesignalbutton.grid(row=11, column=RCOL + 2) # Serial port ========================================================= self.seriallabel = Label(master, text="Serial Port") self.seriallabel.grid(sticky='W', row=7, column=0) self.serialentrystr = StringVar(master, value='/dev/cu.wchusbserial1420') self.serialentry = Entry(master, textvar=self.serialentrystr) self.serialentry.grid(sticky='W', row=7, column=1) self.serialconnectbutton = Button(master, text="Connect", command=self.ConnectToSerial) self.serialconnectbutton.grid(sticky='W', row=7, column=2) self.baudratelabel = Label(master, text="Baud Rate") self.baudratelabel.grid(sticky='W', row=8, column=0) self.baudrateentrystr = StringVar(master, value='115200') self.baudrateentry = Entry(master, textvar=self.baudrateentrystr) self.baudrateentry.grid(sticky='W', row=8, column=1) # Data Logging ======================================================== self.loglabel = Label(master, text="Data Logging") self.loglabel.grid(sticky='W', row=9, column=0) self.logfnameentrystr = StringVar(master, value='SessionLog.txt') self.logfnameentry = Entry(master, textvar=self.logfnameentrystr) self.logfnameentry.grid(sticky='W', row=9, column=1) self.logging_variable = IntVar(master, value=0) self.logging_offbutton = Radiobutton(master, text="Off", variable=self.logging_variable, value=0, width=4) self.logging_offbutton.grid(row=9, column=2) self.logging_onbutton = Radiobutton(master, text="On", variable=self.logging_variable, value=1, width=4) self.logging_onbutton.grid(row=9, column=3) # Abort =============================================================== self.abortbutton = Button(master, text="ABORT", command=self.ABORT) self.abortbutton.grid(row=11, column=0) return
ttk.Label(mighty, text="Choose a number:").grid(column=1, row=0) number = tk.StringVar() number_chosen = ttk.Combobox(mighty, width=12, textvariable=number, state='readonly') number_chosen['values'] = (1, 2, 4, 42, 100) number_chosen.grid(column=1, row=1) number_chosen.current(0) # Spinbox callback def _spin(): value = spin.get() print(value) scrol.insert(tk.INSERT, value + '\n') # Adding a Spinbox widget spin = Spinbox(mighty, values=(1, 2, 4, 42, 100), width=5, bd=9, command=_spin) # using range spin.grid(column=0, row=2) # Using a scrolled Text control scrol_w = 30 scrol_h = 3 scrol = scrolledtext.ScrolledText(mighty, width=scrol_w, height=scrol_h, wrap=tk.WORD) scrol.grid(column=0, row=3, sticky='WE', columnspan=3) # Tab Control 2 refactoring --------------------------------------------------------- # We are creating a container frame to hold all other widgets -- Tab2 mighty2 = ttk.LabelFrame(tab2, text=' The Snake ') mighty2.grid(column=0, row=0, padx=8, pady=4) # Creating three checkbuttons
source = ScrolledText(mainwin, height=10, width=60) source.grid(row=2, column=0, padx=20, pady=(0, 50), columnspan=15) compare = ScrolledText(mainwin, height=10, width=60) compare.grid(row=2, column=16, padx=20, pady=(0, 50), columnspan=15) Label(mainwin, text="Test Case Generator (PYTHON)").grid(row=3, column=0, columnspan=15) generator = ScrolledText(mainwin, height=10, width=60) generator.grid(row=4, rowspan=3, column=0, padx=20, pady=(0, 50), columnspan=15) Label(mainwin, text="Number of Threads: ").grid(row=4, column=17, columnspan=5) spin = Spinbox(mainwin, from_=1, to=16) spin.grid(row=4, column=22) var1 = tk.IntVar() checkbox = tk.Checkbutton(mainwin, text='Use Test Case Instead', variable=var1, onvalue=1, offvalue=0) checkbox.grid(row=5, column=22) tex = "" execute = "" exit = "" continue_executing = True workers = list() test_num = 1
def update_vsc_table(): global vsc_kmh for widget in vsc_tab.winfo_children(): widget.destroy() headers = ['Car', 'Time Over Limit', '', ''] scrollbar = Scrollbar(vsc_tab, orient='vertical') scrollbar.grid(row=0, column=1, sticky='ns') canvas = Canvas(vsc_tab, yscrollcommand=scrollbar.set) canvas.create_image(0, 0, anchor='ne') canvas['scrollregion'] = (0, 0, 0, (len(listed_vsc) + 1) * 30) canvas['width'] = 565 canvas['height'] = 370 canvas.grid(row=0, column=0) scrollbar.config(command=canvas.yview) canvas.config(scrollregion=canvas.bbox("all")) table = Frame(canvas) vsc_label = Label(table, text='VSC speed', width=15, height=2, font='Helvetica 8 bold') cur_vsc_speed = StringVar(table) cur_vsc_speed.set(vsc_kmh) vsc_speed = Spinbox(table, from_=50, to=200, increment=10, state='readonly', width=15, textvariable=cur_vsc_speed) vsc_button = Button( table, text='On/Off', bg='Gray', command=lambda: set_vsc_details(vsc_button, vsc_speed.get())) vsc_label.grid(row=0, column=4, padx=1, pady=1, sticky="nsew") vsc_speed.grid(row=1, column=4, padx=1, pady=1, sticky="nsew") vsc_button.grid(row=2, column=4, padx=1, pady=1, sticky="nsew") table.grid_columnconfigure(0, weight=1) table.grid_columnconfigure(1, weight=1) table.grid_columnconfigure(2, weight=1) for j, column in enumerate(headers): label = Label(table, text=column, width=15, height=2, font='Helvetica 8 bold') label.grid(row=0, column=j, sticky="nsew", padx=1, pady=1) table.grid_columnconfigure(j, weight=1) for i, row in enumerate(listed_vsc): for j, column in enumerate(row): label = Label(table, text=column if j == 0 else f"{float(column):.2f}", bg='Light Gray') label.grid(row=i + 1, column=j, sticky="nsew", padx=1, pady=1) table.grid_columnconfigure(j, weight=1) if j == 1: dismiss_button = Button( table, text="Dismiss", bg='medium sea green', width=5, command=lambda row=i: dismiss_vsc_accident(row)) penalty_button = Button( table, text="Penalty", bg='indian red', width=5, command=lambda row=i: add_vsc_penalty(row)) dismiss_button.grid(row=i + 1, column=j + 1, padx=1, pady=1, sticky="nsew") penalty_button.grid(row=i + 1, column=j + 2, padx=1, pady=1, sticky="nsew") table.grid_columnconfigure(j + 1, weight=1) canvas.create_window((0, 0), window=table, anchor='nw')
class NewMorphWindow(Toplevel): def __init__(self, master=None): super().__init__(master=master) self.set_basic() self.set_widgets() def set_basic(self): self.minsize(500, 300) self.maxsize(500, 300) self.title("Operacje morfologiczne") self.protocol("WM_DELETE_WINDOW", lambda: self.cancel()) self.operations = [ "EROZJA", "DYLACJA", "OTWARCIE", "ZAMKNIĘCIE", "SZKIELETYZACJA" ] self.shapes = ["KWADRAT", "ROMB"] self.handleBorder = { "Bez zmian (isolated)": 0, "Odbicie lustrzane (reflect)": 1, "Powielenie skrajnego piksela (replicate)": 2 } def set_widgets(self): self.operationChoice = StringVar(self, self.operations[0]) self.shape = StringVar(self, value=self.shapes[0]) self.size = StringVar(self, value="3") self.borderType = StringVar(self, list(self.handleBorder.keys())[0]) self.operationChoice.trace("w", self.update_preview) self.shape.trace("w", self.update_preview) self.borderType.trace("w", self.update_preview) self.operationList = OptionMenu(self, self.operationChoice) self.shapeList = OptionMenu(self, self.shape) self.sizeSpin = Spinbox(self, justify='center', font=("Helvetica", 15), from_=3, to=9999, textvariable=self.size, command=self.update_preview, state='readonly', increment=2) self.borderList = OptionMenu(self, self.borderType) for oper in self.operations: self.operationList['menu'].add_command( label=oper, command=lambda v=oper: self.operationChoice.set(v)) for sh in self.shapes: self.shapeList['menu'].add_command( label=sh, command=lambda v=sh: self.shape.set(v)) for border in self.handleBorder: self.borderList['menu'].add_command( label=border, command=lambda v=border: self.borderType.set(v)) self.saveButton = Button(self, image=saveIcon, command=self.update_image) self.cancelButton = Button(self, image=closeIcon, command=self.cancel) self.update_preview() self.place_widgets() def update_image(self): self.master.image.cv2Image = copy.deepcopy(self.master.image.copy) self.master.image.morph_operations( self.operationChoice.get(), self.shape.get(), int(self.size.get()), self.handleBorder[self.borderType.get()]) self.master.image.copy = copy.deepcopy(self.master.image.cv2Image) self.master.manager.new_state(self.master.image.cv2Image) self.master.update_visible_image() self.master.update_child_windows() self.destroy() def update_preview(self, *args): self.master.image.cv2Image = copy.deepcopy(self.master.image.copy) self.master.image.morph_operations( self.operationChoice.get(), self.shape.get(), int(self.size.get()), self.handleBorder[self.borderType.get()]) self.master.update_visible_image() self.master.update_child_windows() def place_widgets(self): Label(self, text="Operacja:", font=("Helvetica", 15)).place(x=25, y=25) Label(self, text="Kształt i rozmiar:", font=("Helvetica", 15)).place(x=25, y=85) Label(self, text="Piksele skrajne:", font=("Helvetica", 15)).place(x=25, y=145) self.operationList.place(width=250, height=50, x=225, y=20) self.shapeList.place(width=100, height=50, x=225, y=80) self.sizeSpin.place(width=100, height=50, x=375, y=80) self.borderList.place(width=250, height=50, x=225, y=140) self.saveButton.place(width=40, height=40, x=200, y=255) self.cancelButton.place(width=40, height=40, x=260, y=255) def cancel(self): self.master.image.cv2Image = copy.deepcopy(self.master.image.copy) self.master.update_visible_image() self.master.image.fill_histogram() self.master.update_child_windows() self.destroy()
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("") # self.style = Style() # self.style.theme_use("clam") # self.pack(fill=BOTH, expand = 1) self.quitbutton = Button(self, text="Quit", command=lambda: self.quit()) self.quitbutton.grid(row=3, column=1, pady=4) self.labelErrorPointer = Label(self, text="◀") self.labellist = [] self.entrylist = [] self.verifylist = [] self.misclist = [] self.optionCreate = "Create" self.optionUpcoming = "Upcoming" self.optionPast = "Past" self.prevmode = self.optionCreate self.curmode = self.optionCreate self.optionvar = tkinter.StringVar(self) self.optionvar.trace("w", self.permaloop) self.optionvar.set(self.optionCreate) self.option = OptionMenu(self, self.optionvar, self.optionCreate, self.optionUpcoming, self.optionPast) self.optionpostmodevar = tkinter.StringVar(self) self.optionpostmodevar.trace("w", self.permaloop) self.optionpostmodevar.set("url") self.optionpostmode = OptionMenu(self, self.optionpostmodevar, "url", "text") self.labelText = Label(self, text="Selftext:") self.entryText = Text(self) self.labelURL = Label(self, text="URL:") self.entryURL = Entry(self) self.entryURL.configure(width=60) self.sql = sqlite3.connect("sql.db") print("Loaded SQL Database") self.cur = self.sql.cursor() self.cur.execute( "CREATE TABLE IF NOT EXISTS upcoming(ID TEXT, SUBREDDIT TEXT, TIME INT, TITLE TEXT, URL TEXT, BODY TEXT)" ) self.cur.execute( "CREATE TABLE IF NOT EXISTS past(ID TEXT, SUBREDDIT TEXT, TIME INT, TITLE TEXT, URL TEXT, BODY TEXT, POSTLINK TEXT)" ) self.cur.execute("CREATE TABLE IF NOT EXISTS internal(NAME TEXT, ID INT)") print("Loaded Completed table") self.cur.execute("SELECT * FROM internal") f = self.cur.fetchone() if not f: print("Database is new. Adding ID counter") self.cur.execute("INSERT INTO internal VALUES(?, ?)", ["counter", 1]) self.idcounter = 1 else: self.idcounter = f[1] print("Current ID counter: " + str(self.idcounter)) self.sql.commit() sw = self.parent.winfo_screenwidth() sh = self.parent.winfo_screenheight() w = 853 h = 480 x = (sw - w) / 2 y = (sh - h) / 2 self.parent.geometry("%dx%d+%d+%d" % (w, h, x, y - 50)) self.login() def login(self): try: self.quitbutton.grid_forget() self.quitbutton.grid(row=9000, column=0, columnspan=20) self.option.grid(row=1, column=0, columnspan=8, pady=8) self.updategui(fullclean=True) except praw.errors.InvalidUserPass: pass print("Invalid username or password") self.entryPassword.delete(0, 200) self.labelErrorPointer.grid(row=1, column=2) def permaloop(self, *args): self.curmode = self.optionvar.get() print("Was: " + self.prevmode + " | Now: " + self.curmode) if self.curmode != self.prevmode: self.prevmode = self.curmode self.updategui(fullclean=True) else: self.updategui(False) def getTime(self, bool): timeNow = datetime.datetime.now(datetime.timezone.utc) timeUnix = timeNow.timestamp() if bool == False: return timeNow else: return timeUnix def addentrytobase(self, subreddit, title, url="", body="", mode="", ptime=""): curtime = round(self.getTime(True)) try: t = ( self.entryMo.get() + " " + self.entryDa.get() + " " + self.entryYr.get() + " " + self.entryHH.get() + ":" + self.entryMM.get() ) plandate = datetime.datetime.strptime(t, "%B %d %Y %H:%M") plandate = plandate.timestamp() except ValueError: print("Invalid Day") return False if mode == "url": url = self.entryURL.get() body = "" if "http://" not in url and "https://" not in url: print("Please enter a proper URL") return False if mode == "text": body = self.entryText.get("1.0", "end") url = "" if plandate < curtime: print("Please enter a time in the future") return False if not all(char in string.ascii_letters + string.digits + "_-" for char in subreddit): print("Subreddit contains invalid characters") return False if len(subreddit) == 0: print("You must enter a subreddit") return False if len(title) == 0: print("You must enter a title") return False if len(title) > 300: print("Title is too long. " + str(len(title)) + "/300 char max") return False if len(body) > 15000: print("Body is too long. " + str(len(body)) + "/15,000 char max") print("Timestamp:", plandate) self.cur.execute( "INSERT INTO upcoming VALUES(?, ?, ?, ?, ?, ?)", [self.idcounter, subreddit, int(plandate), title, url, body], ) self.idcounter += 1 self.cur.execute("UPDATE internal SET ID=? WHERE NAME=?", [self.idcounter, "counter"]) self.sql.commit() print("Post Saved!") self.entryText.delete("1.0", "end") self.entryURL.delete(0, "end") self.entryTitle.delete(0, "end") # self.updategui(halfclean=True) def dropentryfrombase(self, ID): try: ID = int(ID) except ValueError: print("You must enter a number") return print("Dropping Item " + str(ID) + " from Upcoming") self.cur.execute("DELETE FROM upcoming WHERE ID=?", [ID]) self.sql.commit() self.updategui(fullclean=True) def printbasetofile(self, db): filea = open(db + ".txt", "w") if db == "past": self.cur.execute("SELECT * FROM past") if db == "upcoming": self.cur.execute("SELECT * FROM upcoming") f = self.cur.fetchall() print("Printed " + db + " unimpeded to file") for item in f: i = list(item) d = datetime.datetime.fromtimestamp(i[2]) i[2] = datetime.datetime.strftime(d, "%b %d %H:%M") i.remove("") print(str(i)[1:-1], file=filea) filea.close() def updategui(self, halfclean=False, fullclean=False): if self.curmode == self.optionCreate: try: print(self.optionpostmodevar.get()) if self.optionpostmodevar.get() == "url": self.entryText.delete("1.0", "end") self.labelText.grid_forget() self.entryText.grid_forget() self.labelURL.grid(row=8, column=0, columnspan=30) self.entryURL.grid(row=9, column=0, columnspan=12, pady=10) if self.optionpostmodevar.get() == "text": self.entryURL.delete(0, "end") self.labelURL.grid_forget() self.entryURL.grid_forget() self.labelText.grid(row=8, column=0, columnspan=30) self.entryText.configure(width=40, height=8) self.entryText.grid(row=9, column=0, columnspan=12) except AttributeError: pass if fullclean == True: print("Cleaning GUI") for item in self.labellist: item.grid_forget() for item in self.entrylist: item.grid_forget() for item in self.verifylist: item.grid_forget() for item in self.misclist: item.grid_forget() self.labellist = [] self.entrylist = [] self.verifylist = [] self.misclist = [] if self.curmode == self.optionCreate: self.newrowindex = 6 self.labelSubreddit = Label(self, text="Subreddit: /r/") self.labelTitle = Label(self, text="Post title: ") self.entrySubreddit = Entry(self) self.entryTitle = Entry(self) self.labelHH = Label(self, text="Schedule time (Local timezone):") nowlist = datetime.datetime.strftime(datetime.datetime.now(), "%B %d %Y %H %M").split() self.entryMo = Spinbox( self, width=9, values=( "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", ), ) self.entryMo.delete(0, "end") self.entryMo.insert(0, nowlist[0]) self.entryDa = Spinbox(self, width=2, from_=1, to=31) self.entryDa.delete(0, "end") self.entryDa.insert(0, nowlist[1]) self.entryYr = Spinbox(self, width=4, from_=2014, to=2500) self.entryYr.delete(0, "end") self.entryYr.insert(0, nowlist[2]) self.entryHH = Spinbox(self, from_=0, to=23, width=2) self.entryHH.delete(0, "end") self.entryHH.insert(0, nowlist[3]) self.entryMM = Spinbox(self, from_=0, to=59, width=2) self.entryMM.delete(0, "end") self.entryMM.insert(0, nowlist[4]) self.buttonAddentry = Button( self, text="Save", command=lambda: self.addentrytobase( self.entrySubreddit.get(), self.entryTitle.get(), mode=self.optionpostmodevar.get() ), ) self.misclist.append(self.labelSubreddit) self.misclist.append(self.entrySubreddit) self.misclist.append(self.labelHH) self.misclist.append(self.entryHH) self.misclist.append(self.entryMM) self.misclist.append(self.entryMo) self.misclist.append(self.entryDa) self.misclist.append(self.entryYr) self.misclist.append(self.labelTitle) self.misclist.append(self.entryTitle) self.misclist.append(self.buttonAddentry) self.misclist.append(self.optionpostmode) self.misclist.append(self.labelText) self.misclist.append(self.entryText) self.misclist.append(self.labelURL) self.misclist.append(self.entryURL) self.labelSubreddit.grid(row=2, column=0, sticky="e") self.labelTitle.grid(row=3, column=0, sticky="e") self.entrySubreddit.grid(row=2, column=1, columnspan=3, sticky="w") self.entryTitle.grid(row=3, column=1, columnspan=3, sticky="w") self.entryMo.grid(row=4, column=1, sticky="e") self.entryDa.grid(row=4, column=2) self.entryYr.grid(row=4, column=3) self.labelHH.grid(row=4, column=0, sticky="se", pady=5) self.entryHH.grid(row=5, column=1, sticky="e") self.entryMM.grid(row=5, column=2, sticky="w") self.optionpostmode.grid(row=6, column=0, columnspan=20, pady=10) self.buttonAddentry.grid(row=200, column=0, columnspan=20) if self.curmode == self.optionUpcoming: self.cur.execute("SELECT * FROM upcoming") dobutton = True if self.curmode == self.optionPast: self.cur.execute("SELECT * FROM past") dobutton = False if self.curmode == self.optionPast or self.curmode == self.optionUpcoming: self.listboxId = Listbox(self) self.listboxId.configure(width=118, height=20, font=("Courier 8")) self.misclist.append(self.listboxId) self.listboxScroller = Scrollbar(self, orient="horizontal", command=self.listboxId.xview) self.listboxScroller.grid(row=4, column=0, columnspan=900) self.listboxId.grid(row=3, column=0, columnspan=10) self.listboxId.configure(xscrollcommand=self.listboxScroller.set) self.misclist.append(self.listboxScroller) self.buttonPrinter = Button(self, text="Print to .txt file") if self.curmode == self.optionPast: self.buttonPrinter.configure(command=lambda: self.printbasetofile("past")) if self.curmode == self.optionUpcoming: self.buttonPrinter.configure(command=lambda: self.printbasetofile("upcoming")) self.buttonPrinter.grid(row=6, column=0, columnspan=90) self.misclist.append(self.buttonPrinter) if dobutton == True: self.entryDelete = Entry(self) self.buttonDelete = Button( self, text="Delete Item: ", command=lambda: self.dropentryfrombase(self.entryDelete.get()) ) self.buttonDelete.grid(row=5, column=0, sticky="e") self.entryDelete.grid(row=5, column=1, sticky="w") self.misclist.append(self.entryDelete) self.misclist.append(self.buttonDelete) fetched = self.cur.fetchall() for item in fetched: d = datetime.datetime.fromtimestamp(item[2]) info = datetime.datetime.strftime(d, "%b %d %H:%M") if item[4] == "": infx = item[5] if item[5] == "": infx = item[4] if self.curmode == self.optionPast: infy = "." + item[6] else: infy = "" self.listboxId.insert( "end", item[0] + "." * (6 - len(item[0])) + item[1][:10] + "." * (12 - len(item[1][:10])) + info + "." * (15 - len(info[:14])) + item[3][:18] + "." * (20 - len(item[3][:14])) + infx[:45] + "." * (47 - len(infx[:45])) + infy, ) def morerows(self, label, columnm, columnn, limit, *args): self.redditlabel = Label(self, text=label) self.redditlabel.grid(row=self.newrowindex, column=columnm, sticky="e") self.labellist.append(self.redditlabel) self.redditentry = Entry(self) self.redditentry.grid(row=self.newrowindex, column=columnn, columnspan=9) self.entrylist.append(self.redditentry) self.newrowindex += 1 if self.newrowindex >= limit: self.morerowbutton.grid_forget() print(self.newrowindex)
class OOP(): def __init__(self): # Initializer method # Create instance self.win = tk.Tk() self.gui_queue = Queue() # Add a title self.win.title("Python GUI") self.create_widgets() # Modified Button Click Function def click_me(self): self.action.configure(text='Hello ' + self.name.get() + ' ' + self.number_chosen.get()) # self.create_thread() bq.write_to_scrol(self) def use_queues(self, num_loop=5): while True: print(self.gui_queue.get()) def create_thread(self, num_loop=10): self.run_thread = Thread( target=self.method_in_a_thread, args=(num_loop,), ) self.run_thread.setDaemon(True) self.run_thread.start() write_thread = Thread( target=self.use_queues, args=(num_loop,), daemon=True) write_thread.start() def method_in_a_thread(self, num_of_loop=5): print('Hi, how are you?') for idx in range(num_of_loop): sleep(2) self.scrol.insert('insert', f'{idx}\n') print('method_in_thread:', self.run_thread.is_alive()) # Spinbox callback def _spin(self): value = self.spin.get() print(value) self.scrol.insert(tk.INSERT, value + '\n') # GUI Callback def checkCallback(self, *ignored_args): # only enable one checkbutton if self.chVarUn.get(): self.check3.configure(state='disabled') else: self.check3.configure(state='normal') if self.chVarEn.get(): self.check2.configure(state='disabled') else: self.check2.configure(state='normal') # Radiobutton Callback def radCall(self): radSel = self.radVar.get() if radSel == 0: self.mighty2.configure(text='Blue') elif radSel == 1: self.mighty2.configure(text='Gold') elif radSel == 2: self.mighty2.configure(text='Red') # update progressbar in callback loop def run_progressbar(self): self.progress_bar["maximum"] = 100 for i in range(101): sleep(0.05) self.progress_bar["value"] = i # increment progressbar self.progress_bar.update() # have to call update() in loop self.progress_bar["value"] = 0 # reset/clear progressbar def start_progressbar(self): self.progress_bar.start() def stop_progressbar(self): self.progress_bar.stop() def progressbar_stop_after(self, wait_ms=1000): self.win.after(wait_ms, self.progress_bar.stop) def usingGlobal(self): global GLOBAL_CONST print(GLOBAL_CONST) GLOBAL_CONST = 777 print(GLOBAL_CONST) # Exit GUI cleanly def _quit(self): self.win.quit() self.win.destroy() exit() ##################################################################################### def create_widgets(self): tabControl = ttk.Notebook(self.win) # Create Tab Control tab1 = ttk.Frame(tabControl) # Create a tab tabControl.add(tab1, text='Tab 1') # Add the tab tab2 = ttk.Frame(tabControl) # Add a second tab tabControl.add(tab2, text='Tab 2') # Make second tab visible tabControl.pack(expand=1, fill="both") # Pack to make visible # LabelFrame using tab1 as the parent mighty = ttk.LabelFrame(tab1, text=' Mighty Python ') mighty.grid(column=0, row=0, padx=8, pady=4) # Modify adding a Label using mighty as the parent instead of win a_label = ttk.Label(mighty, text="Enter a name:") a_label.grid(column=0, row=0, sticky='W') # Adding a Textbox Entry widget self.name = tk.StringVar() self.name_entered = ttk.Entry(mighty, width=24, textvariable=self.name) self.name_entered.grid(column=0, row=1, sticky='W') # Adding a Button self.action = ttk.Button(mighty, text="Click Me!", command=self.click_me) self.action.grid(column=2, row=1) ttk.Label(mighty, text="Choose a number:").grid(column=1, row=0) number = tk.StringVar() self.number_chosen = ttk.Combobox(mighty, width=14, textvariable=number, state='readonly') self.number_chosen['values'] = (1, 2, 4, 42, 100) self.number_chosen.grid(column=1, row=1) self.number_chosen.current(0) # Adding a Spinbox widget self.spin = Spinbox(mighty, values=(1, 2, 4, 42, 100), width=5, bd=9, command=self._spin) # using range self.spin.grid(column=0, row=2, sticky='W') # align left # Using a scrolled Text control scrol_w = 40 scrol_h = 10 # increase sizes self.scrol = scrolledtext.ScrolledText(mighty, width=scrol_w, height=scrol_h, wrap=tk.WORD) self.scrol.grid(column=0, row=3, sticky='WE', columnspan=3) for child in mighty.winfo_children(): # add spacing to align widgets within tabs child.grid_configure(padx=4, pady=2) # ===================================================================================== # Tab Control 2 ---------------------------------------------------------------------- self.mighty2 = ttk.LabelFrame(tab2, text=' The Snake ') self.mighty2.grid(column=0, row=0, padx=8, pady=4) # Creating three checkbuttons chVarDis = tk.IntVar() check1 = tk.Checkbutton(self.mighty2, text="Disabled", variable=chVarDis, state='disabled') check1.select() check1.grid(column=0, row=0, sticky=tk.W) chVarUn = tk.IntVar() check2 = tk.Checkbutton(self.mighty2, text="UnChecked", variable=chVarUn) check2.deselect() check2.grid(column=1, row=0, sticky=tk.W) chVarEn = tk.IntVar() check3 = tk.Checkbutton(self.mighty2, text="Enabled", variable=chVarEn) check3.deselect() check3.grid(column=2, row=0, sticky=tk.W) # trace the state of the two checkbuttons chVarUn.trace('w', lambda unused0, unused1, unused2: self.checkCallback()) chVarEn.trace('w', lambda unused0, unused1, unused2: self.checkCallback()) # First, we change our Radiobutton global variables into a list colors = ["Blue", "Gold", "Red"] # create three Radiobuttons using one variable self.radVar = tk.IntVar() # Next we are selecting a non-existing index value for radVar self.radVar.set(99) # Now we are creating all three Radiobutton widgets within one loop for col in range(3): curRad = tk.Radiobutton(self.mighty2, text=colors[col], variable=self.radVar, value=col, command=self.radCall) curRad.grid(column=col, row=1, sticky=tk.W) # row=6 # And now adding tooltips tt.create_ToolTip(curRad, 'This is a Radiobutton control') # Add a Progressbar to Tab 2 self.progress_bar = ttk.Progressbar(tab2, orient='horizontal', length=286, mode='determinate') self.progress_bar.grid(column=0, row=3, pady=2) # Create a container to hold buttons buttons_frame = ttk.LabelFrame(self.mighty2, text=' ProgressBar ') buttons_frame.grid(column=0, row=2, sticky='W', columnspan=2) # Add Buttons for Progressbar commands ttk.Button(buttons_frame, text=" Run Progressbar ", command=self.run_progressbar).grid(column=0, row=0, sticky='W') ttk.Button(buttons_frame, text=" Start Progressbar ", command=self.start_progressbar).grid(column=0, row=1, sticky='W') ttk.Button(buttons_frame, text=" Stop immediately ", command=self.stop_progressbar).grid(column=0, row=2, sticky='W') ttk.Button(buttons_frame, text=" Stop after second ", command=self.progressbar_stop_after).grid(column=0, row=3, sticky='W') for child in buttons_frame.winfo_children(): child.grid_configure(padx=2, pady=2) for child in self.mighty2.winfo_children(): child.grid_configure(padx=8, pady=2) # Creating a Menu Bar menu_bar = Menu(self.win) self.win.config(menu=menu_bar) # Add menu items file_menu = Menu(menu_bar, tearoff=0) file_menu.add_command(label="New") file_menu.add_separator() file_menu.add_command(label="Exit", command=self._quit) menu_bar.add_cascade(label="File", menu=file_menu) # Display a Message Box def _msgBox(): msg.showinfo('Python Message Info Box', 'A Python GUI created using tkinter:\nThe year is 2017.') # Add another Menu to the Menu Bar and an item help_menu = Menu(menu_bar, tearoff=0) help_menu.add_command(label="About", command=_msgBox) # display messagebox when clicked menu_bar.add_cascade(label="Help", menu=help_menu) # Change the main windows icon self.win.iconbitmap('pyc.ico') # It is not necessary to create a tk.StringVar() # strData = tk.StringVar() strData = self.spin.get() print("Spinbox value: " + strData) # call function self.usingGlobal() self.name_entered.focus() # Add Tooltips ----------------------------------------------------- # Add a Tooltip to the Spinbox tt.create_ToolTip(self.spin, 'This is a Spinbox control') # Add Tooltips to more widgets tt.create_ToolTip(self.name_entered, 'This is an Entry control') tt.create_ToolTip(self.action, 'This is a Button control') tt.create_ToolTip(self.scrol, 'This is a ScrolledText control')
class OOP(): def __init__(self): # Start TCP/IP server in its own thread svrT = Thread(target=startServer, daemon=True) svrT.start() # Create a Queue self.guiQueue = Queue() # Create instance self.win = tk.Tk() # Add a title self.win.title("Python GUI") self.createWidgets() self.defaultFileEntries() def methodInAThread(self, numOfLoops=10): for idx in range(numOfLoops): time.sleep(1) self.scr.insert(tk.INSERT, str(idx) + '\n') time.sleep(1) def defaultFileEntries(self): self.fileEntry.delete(0, tk.END) self.fileEntry.insert(0, fDir) if len(fDir) > self.entryLen: self.fileEntry.config(width=len(fDir) + 3) self.fileEntry.config(state='readonly') self.netwEntry.delete(0, tk.END) self.netwEntry.insert(0, netDir) if len(netDir) > self.entryLen: self.netwEntry.config(width=len(netDir) + 3) # Button Click event callback function def clickMe(self): #self.action.configure(text='Hello ' + self.name.get()+ ' ' + self.numberChosen.get()) # aLabel.configure(foreground='red') # self.createThread(8) qs.writeToScrol(self) time.sleep(2) htmlData = url.getHtml() print(htmlData) self.scr.insert(tk.INSERT, htmlData) # Radiobutton callback def radCall(self): radSel = self.radVar.get() if radSel == 0: # win.configure(background=colors[0]) self.monty2.configure(text='Blue') elif radSel == 1: # win.configure(background=colors[1]) self.monty2.configure(text='Gold') elif radSel == 2: # win.configure(background=colors[2]) self.monty2.configure(text='Red') # Spinbox callback def _spin(self): value = self.spin.get() print(value) self.scr.insert(tk.INSERT, value + '\n') # Display a message box Callback function def _msgBox(self): # mBox.showinfo('Python Message Info Box', 'A Python GUI created using tkinter: \nThe Year is 2016.') # Warning box # mBox.showwarning('Python Message Warning Box', 'A Python GUI created using tkinter: \nWarning: There might be a bug in this code.') # Error box # mBox.showerror('Python Message Warning Box', 'A Python GUI created using tkinter:\nError: Houston we DO have a serious PROBLEM!') answer = mBox.askyesno("Python Message Dual Choice Box", "Are you sure you really wish to do this?") print(answer) # Menu bar with functionality def _quit(self): self.win.quit() self.win.destroy() exit() def createWidgets(self): # Adding tabs self.tabControl = ttk.Notebook(self.win) self.tab1 = ttk.Frame(self.tabControl) self.tabControl.add(self.tab1, text='Tab 1') self.tabControl.pack(expand=1, fill="both") self.tab2 = ttk.Frame(self.tabControl) self.tabControl.add(self.tab2, text='Tab 2') # Creating a container frame to hold all other widgets self.monty = ttk.LabelFrame(self.tab1, text=' Monty Python ') self.monty.grid(column=0, row=0, padx=8, pady=4) # Second label for second tab self.monty2 = ttk.LabelFrame(self.tab2, text=' The Snake ') self.monty2.grid(column=0, row=0, padx=8, pady=4) # win.resizable(0,0) # Adding a label self.aLabel = ttk.Label(self.monty, text="A label") self.aLabel.grid(column=0, row=0) # Adding a button self.action = ttk.Button(self.monty, text="Click Me!", command=self.clickMe) # Position button in second row, second column (zero-based) self.action.grid(column=2, row=1) # Changing label ttk.Label(self.monty, text="Enter a name:").grid(column=0, row=0, sticky='W') # Adding a textbox entry widget self.name = tk.StringVar() self.nameEntered = ttk.Entry(self.monty, width=24, textvariable=self.name) self.nameEntered.grid(column=0, row=1, sticky=tk.W) self.nameEntered.delete(0, tk.END) self.nameEntered.insert(0, '< default name>') # Place cursor into name Entry #self.nameEntered.focus() self.tabControl.select(1) # Adding combo box widgets ttk.Label(self.monty, text="Choose a number: ").grid(column=1, row=0) self.number = tk.StringVar() self.numberChosen = ttk.Combobox(self.monty, width=14, textvariable=self.number, state='readonly') self.numberChosen['values'] = (1, 2, 4, 42, 100) self.numberChosen.grid(column=1, row=1) self.numberChosen.current(0) # Creating three checkbuttons self.chVarDis = tk.IntVar() self.check1 = tk.Checkbutton(self.monty2, text="Disabled", variable=self.chVarDis, state='disabled') self.check1.select() self.check1.grid(column=0, row=4, sticky=tk.W) self.chVarUn = tk.IntVar() self.check2 = tk.Checkbutton(self.monty2, text="UnChecked", variable=self.chVarUn) self.check2.deselect() self.check2.grid(column=1, row=4, sticky=tk.W) self.chVarEn = tk.IntVar() self.check3 = tk.Checkbutton(self.monty2, text="Enabled", variable=self.chVarEn) self.check3.select() self.check3.grid(column=2, row=4, sticky=tk.W) # Adding Radio buttons self.colors = ["Blue", "Gold", "Red"] # create three radiobuttons self.radVar = tk.IntVar() # Select non-existing index for radVar self.radVar.set(99) # Create three radiobutton widgets with a loop for col in range(3): curRad = 'rad' + str(col) curRad = tk.Radiobutton(self.monty2, text=self.colors[col], variable=self.radVar, value=col, command=self.radCall) curRad.grid(column=col, row=5, sticky=tk.W) # Adding a Spinbox widget # spin = Spinbox(monty, from_=0, to=10, width=5, bd=8, command=_spin) # Adding a Spinbox widget using a set of values self.spin = Spinbox(self.monty, values=(1, 2, 4, 42, 100), width=5, bd=8, command=self._spin) self.spin.grid(column=0, row=2) # Adding a second Spinbox widget self.spin2 = Spinbox(self.monty, values=(0, 50, 100), width=5, bd=8, relief=tk.RAISED, command=self._spin) self.spin2.grid(column=1, row=2) # Using a sccrolled text control self.scrolW = 40 self.scrolH = 10 self.scr = scrolledtext.ScrolledText(self.monty, width=self.scrolW, height=self.scrolH, wrap=tk.WORD) self.scr.grid(column=0, row=3, sticky='W', columnspan=3) # Create a container to hold labels self.labelsFrame = ttk.LabelFrame(self.monty2, text=' Labels in a Frame ') self.labelsFrame.grid(column=0, row=7, padx=20, pady=40) # Place labels into the container element ttk.Label(self.labelsFrame, text="Label1").grid(column=0, row=0) ttk.Label(self.labelsFrame, text="Label2").grid(column=0, row=1) ttk.Label(self.labelsFrame, text="Label3").grid(column=0, row=2) # Add space around labels inside labelFrame for child in self.labelsFrame.winfo_children(): child.grid_configure(padx=8, pady=4) # Place cursor into name Entry self.nameEntered.focus() # Create a menu self.menuBar = Menu(self.win) self.win.config(menu=self.menuBar) self.fileMenu = Menu(self.menuBar, tearoff=0) self.fileMenu.add_command(label="New") self.fileMenu.add_separator() self.fileMenu.add_command(label="Exit", command=self._quit) self.menuBar.add_cascade(label="File", menu=self.fileMenu) self.helpMenu = Menu(self.menuBar, tearoff=0) self.helpMenu.add_command(label="About", command=self._msgBox) self.menuBar.add_cascade(label="Help", menu=self.helpMenu) # Change the main windows icon # win.iconbitmap(r'/usr/bin/python3/icon/path') # Add a tooltip tt.createToolTip(self.spin, 'This is a Spin control.') # Add tooltips for more widgets tt.createToolTip(self.nameEntered, 'This is an entry control.') tt.createToolTip(self.action, 'This is a button control.') tt.createToolTip(self.scr, 'This is a scrolled text control.') ################################################################### # Create Manage Files Frame mngFilesFrame = ttk.LabelFrame(self.tab2, text='Manage Files: ') mngFilesFrame.grid(column=0, row=1, sticky='WE', padx=10, pady=5) # Button Callback def getFilename(): print('hello from getFileName') fDir = path.dirname(__file__) fName = fd.askopenfilename(parent=self.win, initialdir=fDir) # Add widgets to manage files frame lb = ttk.Button(mngFilesFrame, text="Browse to File...", command=getFilename) lb.grid(column=0, row=0, sticky=tk.W) file = tk.StringVar() self.entryLen = self.scrolW self.fileEntry = ttk.Entry(mngFilesFrame, width=self.entryLen, textvariable=file) self.fileEntry.grid(column=1, row=0, sticky=tk.W) logDir = tk.StringVar() self.netwEntry =ttk.Entry(mngFilesFrame, width=self.entryLen, textvariable=logDir) self.netwEntry.grid(column=1, row=1, sticky=tk.W) def copyFile(): import shutil src = self.fileEntry.get() file = src.split('/')[-1] dest = self.netwEntry.get() + '\\' + file try: shutil.copy(src, dest) mBox.showinfo('Copy File to Network', 'Success: File copied.') except FileNotFoundError as err: mBox.showerror('Copy File to Network', '*** Failed to copy file! **\n\n' + str(err)) except Exception as ex: mBox.showerror('Copy File to Network', '*** Failed to copy file! **\n\n' + str(ex)) cb = ttk.Button(mngFilesFrame, text="Copy File to: ", command=copyFile) cb.grid(column=0, row=1, sticky=tk.E) # Add some space around each label for child in mngFilesFrame.winfo_children(): child.grid_configure(padx=6, pady=6) # Running methods in Threads def createThread(self, num): self.runT = Thread(target=self.methodInAThread, args=[num]) self.runT.setDaemon(True) self.runT.start() # textBoxes are the Consumers of Queue data writeT = Thread(target=self.useQueues, daemon=True) writeT.start() # Create queue instances def useQueues(self): # guiQueue = Queue() # create queue instance # print(guiQueue) #for idx in range(10): #guiQueue.put('Message from a queue: ' + str(idx)) #while True: #print(guiQueue.get()) # Now using a class memeber Queue while True: print(self.guiQueue.get())
# rad2.grid(column=1, row=5, sticky=tk.W, columnspan=3) # rad3 = tk.Radiobutton(mighty, text=RED, variable=radVar, value=3, command=radCall) # rad3.grid(column=2, row=5, sticky=tk.W, columnspan=3) #Radiobuttons in einer Schleife erstellen radVar = tk.IntVar() #Eine Variable für 3 Buttons radVar.set(99) #Index, der nicht besetzt ist for col in range(3): curRad = tk.Radiobutton(mighty2, text=colors[col], variable=radVar, value=col, command=radCall) curRad.grid(column=col, row=5, sticky=tk.W) #Spinbox (param= Label od. Fenster, Wertebereich von-bis, Größe der Box, Rahmengröße,, Rahmenstyle Event # statt from_ + to kann auch values=(0,50,42,100) benutz werden # Arten von Bordern: tk.SUNKEN, tk.RAISED, tk.FLAT, tk.GROOVE, tk.RIDGE spin = Spinbox(mighty, from_=0, to=10, width=5, bd=8, relief=tk.SUNKEN, command=_spin) spin.grid(column=0, row=2) #Scrollbarer Text(Param:Größe der Box + Umbruch per Wort) scrol_w = 30 scrol_h = 3 scr = scrolledtext.ScrolledText(mighty, width=scrol_w, height=scrol_h, wrap=tk.WORD) scr.grid(column=0, row=6, sticky='WE', columnspan=3) #Container für Labels (param=text, + Feld in der Tabelle, Padding) buttons_frame = ttk.LabelFrame(mighty2, text=' Labels in a Frame ') buttons_frame.grid(column=1, row=7) #oder (column=1,padx=20, pady=40 für Mitte) #Labels in Container setzen ttk.Button(buttons_frame, text="Run Progressbar" , command= run_progressbar ).grid(column=0, row=0, sticky=tk.W) ttk.Button(buttons_frame, text="Start Progressbar" , command= start_progressbar).grid(column=1, row=0, sticky=tk.W)
class NavigationForTableFrame(Frame): ''' This class is responsible for navigation over the table object. Table rows are displayed page by page. This class provides buttons that allow to navigate from page to page. Attributes: table (TableFrame or any object that has attribute nb_rows and implements display_data method): table that should be navigated. goto_spin (Spinbox): Spinbox widget that allows to enter page number and to switch between pages. text_var_nb_pages (StringVar): text variable that shows total number of pages. current_page_str (StringVar): text variable that stores currently displayed page. Args: parent (Tk object): parent for this frame. table (TableFrameWithInputOutputBox): table with multiple pages that will be navigated by this frame. ''' def __init__(self, parent, table, *args, **kw): super().__init__(parent, *args, **kw) self.table = table self.goto_spin = None self.text_var_nb_pages = StringVar() self.current_page_str = StringVar() self.create_widgets() def create_widgets(self): ''' Creates all necessary widgets for navigation. ''' prev_btn = Button(self, text='<<', width=5, command=self.show_prev_page) prev_btn.grid(row=0, column=0, sticky=N, padx=3) next_btn = Button(self, text='>>', width=5, command=self.show_next_page) next_btn.grid(row=0, column=1, sticky=N) goto_lbl = Label(self, text='Go to') goto_lbl.grid(row=0, column=3, sticky=N, padx=5) self.goto_spin = Spinbox(self, width=7, from_=1, to=1, textvariable=self.current_page_str, command=self.on_page_change) self.goto_spin.bind('<Return>', self.on_page_change) self.goto_spin.grid(row=0, column=4, sticky=N, padx=5) nb_pages_lb = Label(self, textvariable=self.text_var_nb_pages) nb_pages_lb.grid(row=0, column=5, sticky=W+N, padx=5) self.reset_navigation() def show_prev_page(self): ''' Displays previous page. This method is called when user presses button '<<'. If the first page is currently displayed and the method is called, then the call to this method is ignored. ''' prev_page_index = int(self.current_page_str.get()) - 1 if prev_page_index > 0: self.current_page_str.set(prev_page_index) self.on_page_change() def show_next_page(self): ''' Displays next page. This method is called when user presses button '>>'. If the last page is currently displayed and the method is called, then the call to this method is ignored. ''' next_page_index = int(self.current_page_str.get()) + 1 if next_page_index <= int(self.goto_spin.cget('to')): self.current_page_str.set(next_page_index) self.on_page_change() def on_page_change(self, *args): ''' Displays a page which number is currently stored in current_page_str. This method is called in show_next_page(), show_prev_page() and when the user enters data and presses Enter. args are supplied by Return event. If the entered value is invalid, then the first page is displayed. If the entered value is zero or negative, then the first page is isplayed. If the entered value is larger than the total number of pages, then the last page is displayed. ''' try: curr_page = int(self.current_page_str.get()) except ValueError: curr_page = 1 self.current_page_str.set(curr_page) max_page = int(self.goto_spin.cget('to')) if curr_page > max_page: curr_page = max_page self.current_page_str.set(curr_page) if curr_page <= 0: curr_page = 1 self.current_page_str.set(curr_page) # second -1 because row indeces start with 0 row_index = calculate_start_row_index(curr_page, self.table.nb_rows) self.table.display_data(row_index) def reset_navigation(self): ''' Resets navigation parameters. Sets current page number to 1 and total number of pages to zero. ''' self.current_page_str.set('1') self.text_var_nb_pages.set('1 pages') self.goto_spin.config(to=1) def set_navigation(self, nb_data_pages, reset_curr_page=True): ''' Sets navigation parameters. Sets current page number to 1 and total number of pages to nb_data_pages. Args: nb_data_pages (int): new value for the total number of pages. reset_curr_page (bool): True is current page must be reset to 1, False otherwise. ''' self.goto_spin.config(to=nb_data_pages) if reset_curr_page: self.current_page_str.set('1') self.text_var_nb_pages.set('{0} pages'.format(nb_data_pages))
from tkinter import Tk, Spinbox from tkinter.ttk import Style, Label, Button, Combobox top = Tk() Style().configure("TButton", foreground='white', background='red') Label(top, text='Animals (in pairs; min: pair, max: dozen)').pack() Spinbox(top, from_=2, to=12, increment=2, font='Helvetica -14 bold').pack() Label(top, text='Type: ').pack() Combobox(top, values=('dog', 'cat', 'hamster', 'python')).pack() Button(top, text='QUIT', command=top.quit, style='TButton').pack() top.mainloop()
ttk.Label(monty, text="Choose a number:").grid(column=1, row=0) number = tk.StringVar() numberChosen = ttk.Combobox(monty, width=12, textvariable=number) numberChosen['values'] = (1, 2, 4, 42, 100) numberChosen.grid(column=1, row=1) numberChosen.current(0) # Spinbox callback def _spin(): value = spin.get() print(value) scr.insert(tk.INSERT, value + '\n') # Adding a Spinbox widget using a set of values spin = Spinbox(monty, values=(1, 2, 4, 42, 100), width=5, bd=8, command=_spin) spin.grid(column=0, row=2) # Add a Tooltip createToolTip(spin, 'This is a Spin control.') # Using a scrolled Text control scrolW = 30; scrolH = 3 scr = scrolledtext.ScrolledText(monty, width=scrolW, height=scrolH, wrap=tk.WORD) scr.grid(column=0, row=3, sticky='WE', columnspan=3) # Tab Control 2 refactoring ----------------------------------------- # We are creating a container frame to hold all other widgets -- Tab2 monty2 = ttk.LabelFrame(tab2, text=' The Snake ') monty2.grid(column=0, row=0, padx=8, pady=4)
scr['bg'] = 'white' scr.bind('<Enter>', scr_hover) scr.bind('<Leave>', scr_leave) def _spin(): value = spin.get() scr.insert(tk.INSERT, 'Input = %s \n' % value) spin = Spinbox(gui, from_=0, to=10, width=5, bd=8, relief=tk.FLAT, command=_spin) spin.grid(column=0, row=0, padx=10, pady=10) label = tk.Label(gui, text='Guest') label.grid(column=1, row=0, padx=10, pady=10) def spin_hover(event): spin['bg'] = 'gray94' def spin_leave(event): spin['bg'] = 'white'
class OOP(): def __init__(self): self.win = tk.Tk() self.win.title('Python GUI') self.win.iconbitmap(r'C:\Anaconda3\DLLs\pyc.ico') self.createWidgets() # add button click callback function def clickMe(self): self.action.configure(text="Hello " + self.name.get() + ' ' + self.numberChosen.get()) # display message back # callback function def _msgBox(self) : mBox.showinfo('Python Message Info Box','A Python GUI created using tkinter:\n\nThe year is 2016.') # mBox.showwarning('Python Message Warning Box','A Python GUI created using tkinter:\n\n' # 'Warning: There might be a bug in this code') # mBox.showerror('Python Message Error Box','A Python GUI created using tkinter:\n\nError: Housseton ~ we DO have a serious PROBLEM!') answer = mBox.askyesno('Python Message Dual Choice Box', 'Are ou sure you really wish to do this?') print(answer) # radiobutton callback def radCall(self): radSel = self.radVar.get() if radSel == 0: self.monty2.configure(text='Blue') elif radSel == 1: self.monty2.configure(text='Gold') elif radSel == 2: self.monty2.configure(text='Red') # spin callback def _spin(self): value = self.spin.get() print(value) self.scr.insert(tk.INSERT, value + '\n') def createWidgets(self): tabControl= ttk.Notebook(self.win) tab1=ttk.Frame(tabControl) tabControl.add(tab1, text='Tab 1') tab2 = ttk.Frame(tabControl) tabControl.add(tab2, text='Tab 2') tab3 = ttk.Frame(tabControl) tabControl.add(tab3, text='Tab 3') tabControl.pack(expand=1, fill='both') tab3=tk.Frame(tab3,bg='blue') tab3.pack() for orangeColor in range(2): canvas = tk.Canvas(tab3, width=150,height=80,highlightthickness=0,bg='orange') canvas.grid(row=orangeColor,column=orangeColor) # create container to hold all widgets self.monty = ttk.LabelFrame(tab1,text=' Monty Python ') self.monty.grid(column=0,row=0,padx=8,pady=4) self.monty2 = ttk.LabelFrame(tab2,text=' The Snake ') self.monty2.grid(column=0,row=0,padx=8,pady=4) #Label ttk.Label(self.monty,text="Enter a name:").grid(column=0,row=0,sticky='W') #add a text box widget name = tk.StringVar() self.nameEntered = ttk.Entry(self.monty, width=12, textvariable=name) self.nameEntered.grid(column=0,row=1,sticky=tk.W) tt.createToolTip(self.nameEntered, 'This is an entry control') # combo box and label ttk.Label(self.monty, text='Choose a number:').grid(column=1, row=0) number = tk.StringVar() numberChosen = ttk.Combobox(self.monty, width=12, textvariable=number, state='readonly') numberChosen['values'] = (1,2,4,42,100) numberChosen.grid(column=1, row=1) numberChosen.current(0) # add a button action = ttk.Button(self.monty, text="Click Me!", command=self.clickMe) action.grid(column=2, row=1) #action.configure(state='disabled') #add check boxes chVarDis = tk.IntVar() check1 = tk.Checkbutton(self.monty2, text='Disabled',variable=chVarDis, state='disabled') check1.select() check1.grid(column=0,row=4, sticky=tk.W) chVarUn = tk.IntVar() check2 = tk.Checkbutton(self.monty2, text='UnChecked',variable=chVarUn) check2.deselect() check2.grid(column=1,row=4,sticky=tk.W) chVarEn = tk.IntVar() check3 = tk.Checkbutton(self.monty2, text='Enabled',variable=chVarEn) check3.select() check3.grid(column=2,row=4,sticky=tk.W) # Radiobutton list colors = ["Blue", "Gold", "Red"] #create three radio buttons self.radVar=tk.IntVar() self.radVar.set(99) for col in range(3): curRad = 'rad' + str(col) curRad = tk.Radiobutton(self.monty2, text=colors[col], variable=self.radVar, value = col, command=self.radCall) curRad.grid(column=col, row=5, sticky=tk.W) #add a spinbox self.spin = Spinbox(self.monty,from_=0,to=10,width=5,bd=8, command=self._spin) self.spin.grid(column=0,row=2) # add a tooltip tt.createToolTip(self.spin,'This is a Spin control.') spin2 = Spinbox(self.monty, values=(0,50,100),width=5,bd=10,command=self._spin,relief=tk.RIDGE) spin2.grid(column=1,row=2) # add scrolled text widget scrolW= 50 scrolH = 3 self.scr = scrolledtext.ScrolledText(self.monty, width=scrolW, height=scrolH, wrap=tk.WORD) self.scr.grid(column=0, sticky='WE',columnspan=3) #scr.grid(column=0, columnspan=3) tt.createToolTip(self.scr,'This is a ScrolledText widget.') # container to hold labels labelsFrame = ttk.LabelFrame(self.monty, text=' Labels in a Frame ') labelsFrame.grid(column=0,row=7,padx=20,pady=40) # place labels into the container ttk.Label(labelsFrame,text='Label1').grid(column=0,row=0) ttk.Label(labelsFrame,text='Label2').grid(column=0,row=1) ttk.Label(labelsFrame,text='Label3').grid(column=0,row=2) for child in labelsFrame.winfo_children(): child.grid_configure(padx=8,pady=4) # menu commands def _quit(self): self.win.quit() self.win.destroy() exit() #create menubar menuBar=Menu(self.win) self.win.config(menu=menuBar) # add menu items fileMenu = Menu(menuBar, tearoff=0) fileMenu.add_command(label='New') fileMenu.add_separator() fileMenu.add_command(label='Exit', command=_quit) menuBar.add_cascade(label='File',menu=fileMenu) helpMenu = Menu(menuBar,tearoff=0) helpMenu.add_command(label='About',command=self._msgBox) menuBar.add_cascade(label='Help',menu=helpMenu)
def createWidgets(self): # Tab Control introduced here -------------------------------------- tabControl = ttk.Notebook(self.win) # Create Tab Control tab1 = ttk.Frame(tabControl) # Create a tab tabControl.add(tab1, text='Tab 1') # Add the tab tab2 = ttk.Frame(tabControl) # Add a second tab tabControl.add(tab2, text='Tab 2') # Make second tab visible tabControl.pack(expand=1, fill="both") # Pack to make visible # ~ Tab Control introduced here ----------------------------------------- # We are creating a container frame to hold all other widgets self.monty = ttk.LabelFrame(tab1, text=' Monty Python ') self.monty.grid(column=0, row=0, padx=8, pady=4) # Changing our Label ttk.Label(self.monty, text="Enter a name:").grid(column=0, row=0, sticky='W') # Adding a Textbox Entry widget self.name = tk.StringVar() nameEntered = ttk.Entry(self.monty, width=12, textvariable=self.name) nameEntered.grid(column=0, row=1, sticky='W') # Adding a Button self.action = ttk.Button(self.monty, text="Click Me!", command=self.clickMe) self.action.grid(column=2, row=1) ttk.Label(self.monty, text="Choose a number:").grid(column=1, row=0) number = tk.StringVar() numberChosen = ttk.Combobox(self.monty, width=12, textvariable=number) numberChosen['values'] = (1, 2, 4, 42, 100) numberChosen.grid(column=1, row=1) numberChosen.current(0) # Adding a Spinbox widget using a set of values self.spin = Spinbox(self.monty, values=(1, 2, 4, 42, 100), width=5, bd=8, command=self._spin) self.spin.grid(column=0, row=2) # Using a scrolled Text control scrolW = 30; scrolH = 3 self.scr = scrolledtext.ScrolledText(self.monty, width=scrolW, height=scrolH, wrap=tk.WORD) self.scr.grid(column=0, row=3, sticky='WE', columnspan=3) # TODO: ch11 new #------------------------------------------------------------------------- #------------------------------------------------------------------------- # Adding another Button self.action = ttk.Button(self.monty, text="Clear Text", command=self.clearScrol) self.action.grid(column=2, row=2) # Adding more Feature Buttons startRow = 4 for idx in range(12): if idx < 2: colIdx = idx col = colIdx else: col += 1 if not idx % 3: startRow += 1 col = 0 b = ttk.Button(self.monty, text="Feature " + str(idx+1)) b.grid(column=col, row=startRow) # Tab Control 3 ----------------------------------------- tab3 = ttk.Frame(tabControl) # Add a tab tabControl.add(tab3, text='Tab 3') # Make tab visible # We are creating a container frame to hold all other widgets -- Tab3 monty3 = ttk.LabelFrame(tab3, text=' New Features ') monty3.grid(column=0, row=0, padx=8, pady=4) # Adding more Feature Buttons startRow = 4 for idx in range(24): if idx < 2: colIdx = idx col = colIdx else: col += 1 if not idx % 3: startRow += 1 col = 0 b = ttk.Button(monty3, text="Feature " + str(idx+1)) b.grid(column=col, row=startRow) # Add some space around each label for child in monty3.winfo_children(): child.grid_configure(padx=8) #------------------------------------------------------------------------- # TODO: ch11 new end # Tab Control 2 refactoring ----------------------------------------- # We are creating a container frame to hold all other widgets -- Tab2 self.monty2 = ttk.LabelFrame(tab2, text=' Holy Grail ') self.monty2.grid(column=0, row=0, padx=8, pady=4) # Creating three checkbuttons chVarDis = tk.IntVar() check1 = tk.Checkbutton(self.monty2, text="Disabled", variable=chVarDis, state='disabled') check1.select() check1.grid(column=0, row=0, sticky=tk.W) self.chVarUn = tk.IntVar() self.check2 = tk.Checkbutton(self.monty2, text="UnChecked", variable=self.chVarUn) self.check2.deselect() self.check2.grid(column=1, row=0, sticky=tk.W ) self.chVarEn = tk.IntVar() self.check3 = tk.Checkbutton(self.monty2, text="Toggle", variable=self.chVarEn) self.check3.deselect() self.check3.grid(column=2, row=0, sticky=tk.W) # trace the state of the two checkbuttons self.chVarUn.trace('w', lambda unused0, unused1, unused2 : self.checkCallback()) self.chVarEn.trace('w', lambda unused0, unused1, unused2 : self.checkCallback()) # ~ Tab Control 2 refactoring ----------------------------------------- # Radiobutton list colors = ["Blue", "Gold", "Red"] self.radVar = tk.IntVar() # Selecting a non-existing index value for radVar self.radVar.set(99) # Creating all three Radiobutton widgets within one loop for col in range(3): curRad = 'rad' + str(col) curRad = tk.Radiobutton(self.monty2, text=colors[col], variable=self.radVar, value=col, command=self.radCall) curRad.grid(column=col, row=6, sticky=tk.W, columnspan=3) # And now adding tooltips tt.createToolTip(curRad, 'This is a Radiobutton control.') # Create a container to hold labels labelsFrame = ttk.LabelFrame(self.monty2, text=' Labels in a Frame ') labelsFrame.grid(column=0, row=7) # Place labels into the container element - vertically ttk.Label(labelsFrame, text="Label1").grid(column=0, row=0) ttk.Label(labelsFrame, text="Label2").grid(column=0, row=1) # Add some space around each label for child in labelsFrame.winfo_children(): child.grid_configure(padx=8) # Creating a Menu Bar menuBar = Menu(tab1) self.win.config(menu=menuBar) # Add menu items fileMenu = Menu(menuBar, tearoff=0) fileMenu.add_command(label="New") fileMenu.add_separator() fileMenu.add_command(label="Exit", command=self._quit) menuBar.add_cascade(label="File", menu=fileMenu) # Add another Menu to the Menu Bar and an item helpMenu = Menu(menuBar, tearoff=0) helpMenu.add_command(label="About") menuBar.add_cascade(label="Help", menu=helpMenu) # Change the main windows icon self.win.iconbitmap(r'C:\Python34\DLLs\pyc.ico') # Using tkinter Variable Classes strData = tk.StringVar() strData.set('Hello StringVar') print(strData.get()) # Default tkinter Variable Classes intData = tk.IntVar() print(intData.get()) print(tk.DoubleVar()) print(tk.BooleanVar()) # It is not necessary to create a tk.StringVar() strData = tk.StringVar() strData = self.spin.get() print("Hello " + strData) # Printing the Global works print(GLOBAL_CONST) # call method self.usingGlobal() # Place cursor into name Entry nameEntered.focus() # Add a Tooltip to the Spinbox tt.createToolTip(self.spin, 'This is a Spin control.') # Add Tooltips to more widgets tt.createToolTip(nameEntered, 'This is an Entry control.') tt.createToolTip(self.action, 'This is a Button control.') tt.createToolTip(self.scr, 'This is a ScrolledText control.')
ttk.Label(monty, text="Choose a number:").grid(column=1, row=0) number = tk.StringVar() numberChosen = ttk.Combobox(monty, width=12, textvariable=number) numberChosen['values'] = (1, 2, 4, 42, 100) numberChosen.grid(column=1, row=1) numberChosen.current(0) # Spinbox callback def _spin(): value = spin.get() print(value) scr.insert(tk.INSERT, value + '\n') # Adding a Spinbox widget using a set of values spin = Spinbox(monty, values=(1, 2, 4, 42, 100), width=5, bd=8, command=_spin) spin.grid(column=0, row=2) # Add a Tooltip createToolTip(spin, 'This is a Spin control.') # Using a scrolled Text control scrolW = 30; scrolH = 3 scr = scrolledtext.ScrolledText(monty, width=scrolW, height=scrolH, wrap=tk.WORD) scr.grid(column=0, row=3, sticky='WE', columnspan=3) # Tab Control 2 refactoring ----------------------------------------- # We are creating a container tab3 to hold all other widgets -- Tab2 monty2 = ttk.LabelFrame(tab2, text=' The Snake ') monty2.grid(column=0, row=0, padx=8, pady=4)
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("") #self.style = Style() #self.style.theme_use("clam") #self.pack(fill=BOTH, expand = 1) self.labelU = Label(self, text="U:") self.labelP = Label(self, text="P:") self.mailrecipient = 'GoldenSights' self.entryUsername = Entry(self) self.entryUsername.focus_set() self.entryUsername.bind('<Return>', lambda event: self.entryPassword.focus_set()) self.entryPassword = Entry(self) self.entryPassword.config(show='•') self.entryPassword.bind('<Return>', lambda event: self.login(self.entryUsername.get(), self.entryPassword.get())) self.newbutton = Button(self, text="Login", command= lambda: self.login(self.entryUsername.get(), self.entryPassword.get())) self.newbutton.bind('<Return>', lambda event: self.login(self.entryUsername.get(), self.entryPassword.get())) self.newbutton.config(width=6) self.quitbutton = Button(self, text="Quit", command= lambda: self.quit()) self.quitbutton.config(width=6) self.labelU.grid(row=0, column=0,padx=0) self.entryUsername.grid(row=0, column=1) self.labelP.grid(row=1, column=0) self.entryPassword.grid(row=1, column=1, pady=4) self.newbutton.grid(row=2, column=1) self.quitbutton.grid(row=3, column=1, pady=4) self.labelErrorPointer = Label(self, text="◀") self.indicatorGreen = PhotoImage(file="indicatorGreen.gif") self.indicatorRed = PhotoImage(file="indicatorRed.gif") self.indicatorBlue = PhotoImage(file="indicatorBlue.gif") self.indicatorBlack = PhotoImage(file="indicatorBlack.gif") sw = self.parent.winfo_screenwidth() sh = self.parent.winfo_screenheight() w=400 h=480 x = (sw - w) / 2 y = (sh - h) / 2 self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y-50)) def login(self, username, password): print('U: ' + username) self.username = username if username == '' or not all(char in string.ascii_letters+string.digits+'_-' for char in username): print('Please enter a username') self.entryUsername.focus_set() self.labelErrorPointer.grid(row=0, column=2) elif password == '': print('Please enter a password') self.entryPassword.focus_set() self.labelErrorPointer.grid(row=1, column=2) else: self.labelErrorPointer.grid_forget() print('Attempting login for ' + username) try: self.USERAGENT = username + ' practices Tkinter+PRAW mixing with utility by /u/GoldenSights.' self.r = praw.Reddit(self.USERAGENT) #self.r.login(username, password) print('Success') self.labelU.grid_forget() self.labelP.grid_forget() self.entryUsername.grid_forget() self.entryPassword.grid_forget() self.newbutton.grid_forget() self.quitbutton.grid_forget() self.usernamelabel = Label(self, text=username + ', Sending to /u/' + self.mailrecipient) self.usernamelabel.grid(row=0, column=0, columnspan=8) self.quitbutton.grid(row=900, column=0) self.labellist = [] self.entrylist = [] self.verifylist = [] self.misclist = [] self.optionDiscuss = "Discussion Flair + Crossposting" self.optionRegister = "Register a new Candidate" self.prevmode = self.optionDiscuss self.curmode = self.optionDiscuss self.optionvar = tkinter.StringVar(self) self.optionvar.trace("w",self.permaloop) self.optionvar.set(self.optionDiscuss) self.option = OptionMenu(self, self.optionvar, self.optionDiscuss, self.optionRegister, "three", "four") self.newbutton.unbind("<Return>") self.entryUsername.unbind("<Return>") self.entryPassword.unbind("<Return>") self.option.grid(row=1,column=0,columnspan=8,pady=8) self.updategui(True) except praw.errors.InvalidUserPass: pass print('Invalid username or password') self.entryPassword.delete(0,200) self.labelErrorPointer.grid(row=1, column=2) def permaloop(self, *args): self.curmode = self.optionvar.get() print('Was: ' + self.prevmode + ' | Now: ' + self.curmode) if self.curmode != self.prevmode: self.prevmode = self.curmode self.updategui(True) def updategui(self, *args): if args[0] == True: print('Cleaning GUI') for item in self.labellist: item.grid_forget() for item in self.entrylist: item.grid_forget() for item in self.verifylist: item.grid_forget() for item in self.misclist: item.grid_forget() self.labellist = [] self.entrylist = [] self.verifylist = [] self.misclist = [] if self.curmode == self.optionDiscuss: self.newrowindex = 4 self.labelPermalink = Label(self, text="Thread Permalink:") self.entryPermalink = Entry(self) self.rowconfigure(2,weight=2) self.labelPermalink.grid(row=2,column=0) self.entryPermalink.grid(row=2,column=1) self.labelcrossposting = Label(self,text="Crosspost to:") self.labelcrossposting.grid(row=3,column=0,columnspan=2,sticky="w") for m in range(5): self.redditlabel = Label(self,text="/r/") self.redditlabel.grid(row=self.newrowindex,column=0, sticky="e") self.labellist.append(self.redditlabel) self.redditentry = Entry(self) self.redditentry.grid(row=self.newrowindex,column=1) self.entrylist.append(self.redditentry) self.newrowindex +=1 self.morerowbutton = Button(self,text="+row",command=lambda: self.morerows('/r/', 0, 1, 20)) self.morerowbutton.grid(row=898,column=0,columnspan=2) self.verifybutton = Button(self,text="Verify",command= lambda: self.updategui(False)) self.verifybutton.grid(row=899,column=0,columnspan=2) self.newrowindex += 2 self.misclist.append(self.labelPermalink) self.misclist.append(self.labelcrossposting) self.misclist.append(self.entryPermalink) self.misclist.append(self.morerowbutton) self.misclist.append(self.verifybutton) if self.curmode == self.optionRegister: self.newrowindex = 6 self.labelCanUsername = Label(self, text="Candidate's Username: /u/") self.entryCanUsername = Entry(self) self.labelCanRealname = Label(self, text="Candidate's Realname:") self.entryCanRealname = Entry(self) self.labelCanFlair = Label(self, text="Candidate's Flair:") self.entryCanFlair = Entry(self) self.entryMo = Spinbox(self, width=9, values=('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')) self.entryDa = Spinbox(self, width=2, from_=1, to=31) self.entryYr = Spinbox(self, width=4, from_=2014, to=2500) self.labelHH = Label(self, text="Schedule time UTC:") self.entryHH = Spinbox(self, from_=0, to=23, width=2) self.entryMM = Spinbox(self, from_=0, to=59, width=2) self.entryYr.delete(0,'end') self.entryYr.insert(0,2014) self.morerowbutton = Button(self,text="+question",command=lambda: self.morerows('Q:', 0, 1, 25)) self.morerowbutton.grid(row=898,column=0,columnspan=8) self.verifybutton = Button(self,text="Verify",command= lambda: self.updategui(False)) self.verifybutton.grid(row=899,column=0,columnspan=8) self.misclist.append(self.labelCanUsername) self.misclist.append(self.labelCanRealname) self.misclist.append(self.entryCanUsername) self.misclist.append(self.entryCanRealname) self.misclist.append(self.labelHH) self.misclist.append(self.entryHH) self.misclist.append(self.entryMM) self.misclist.append(self.entryMo) self.misclist.append(self.entryDa) self.misclist.append(self.entryYr) self.labelCanUsername.grid(row=2, column=0, sticky="e") self.labelCanRealname.grid(row=3, column=0, sticky="e") self.entryCanUsername.grid(row=2, column=1, columnspan=3) self.entryCanRealname.grid(row=3, column=1, columnspan=3) self.entryMo.grid(row=4, column=1,sticky="e") self.entryDa.grid(row=4, column=2) self.entryYr.grid(row=4, column=3) self.labelHH.grid(row=4, column=0, sticky="se", pady=5) self.entryHH.grid(row=5, column=1, sticky="e") self.entryMM.grid(row=5, column=2, sticky="w") else: if self.curmode == self.optionDiscuss: verifies = [] i = self.entryPermalink.get() if len(i) == 6: pid = i else: if 'www.reddit.com/r/' in i and '/comments/' in i: pid = i.split('/comments/')[1].split('/')[0] if 'http://redd.it/' in i: pid = i.split('redd.it/')[1] for flag in self.verifylist: flag.grid_forget() self.verifylist.remove(flag) try: print('Fetching Submission ' + pid) self.r.get_info(thing_id="t3_" + pid).title + 'Check' self.redditlabel = Label(self, image=self.indicatorGreen) self.redditlabel.grid(row=2,column=2) self.verifylist.append(self.redditlabel) verifies.append(True) print('\tSuccess') except: print('Failed. Make sure to include the http://. Copy and paste straight from your browser for best result') self.redditlabel = Label(self, image=self.indicatorRed) self.redditlabel.grid(row=2,column=2) self.verifylist.append(self.redditlabel) verifies.append(False) for entry in self.entrylist: i = entry.get() if i != '': print('Fetching /r/' + i) if all(char in string.ascii_letters+string.digits+'_-' for char in i): try: sub = self.r.get_subreddit(i,fetch=True) self.redditlabel = Label(self, image=self.indicatorGreen) self.redditlabel.grid(row=entry.grid_info()['row'],column=2) self.verifylist.append(self.redditlabel) verifies.append(True) print('\tSuccess') except: self.redditlabel = Label(self, image=self.indicatorRed) self.redditlabel.grid(row=entry.grid_info()['row'],column=2) self.verifylist.append(self.redditlabel) verifies.append(False) print('\tFailed') time.sleep(2) else: self.redditlabel = Label(self, image=self.indicatorRed) self.redditlabel.grid(row=entry.grid_info()['row'],column=2) self.verifylist.append(self.redditlabel) verifies.append(False) print('\tFailed') print(verifies) if self.curmode == self.optionRegister: verifies = [] u=self.entryCanUsername.get() print('Fetching /u/' + u) if not all(char in string.ascii_letters+string.digits+'_-' for char in u): self.redditlabel = Label(self, image=self.indicatorRed) self.redditlabel.grid(row=2, column=4) self.verifylist.append(self.redditlabel) verifies.append(False) print('\tBad characterage') else: try: u = self.r.get_redditor(u) print(u) self.redditlabel = Label(self, image=self.indicatorGreen) self.redditlabel.grid(row=2,column=4) self.verifylist.append(self.redditlabel) verifies.append(True) print('\tSuccess') except: self.redditlabel = Label(self, image=self.indicatorRed) self.redditlabel.grid(row=2,column=4) self.verifylist.append(self.redditlabel) verifies.append(False) print('\tFailed') try: print('Checking Time') t = self.entryMo.get() + ' ' + self.entryDa.get() + ' ' + self.entryYr.get() + ' ' + self.entryHH.get() + ':' + self.entryMM.get() plandate = datetime.datetime.strptime(t, "%B %d %Y %H:%M") plandate = datetime.datetime.utcfromtimestamp(plandate.timestamp()) print('\t' + str(plandate.timestamp())) self.redditlabel = Label(self, image=self.indicatorGreen) self.redditlabel.grid(row=5,column=3) self.verifylist.append(self.redditlabel) verifies.append(True) except: print('\tFailed') self.redditlabel = Label(self, image=self.indicatorRed) self.redditlabel.grid(row=5,column=3) self.verifylist.append(self.redditlabel) verifies.append(False) print(verifies) def morerows(self, label, columnm, columnn, limit, *args): self.redditlabel = Label(self,text=label) self.redditlabel.grid(row=self.newrowindex,column=columnm, sticky="e") self.labellist.append(self.redditlabel) self.redditentry = Entry(self) self.redditentry.grid(row=self.newrowindex,column=columnn, columnspan=8) self.entrylist.append(self.redditentry) self.newrowindex += 1 if self.newrowindex >= limit: self.morerowbutton.grid_forget() print(self.newrowindex)
def createWidgets(self): # Tab Control introduced here -------------------------------------- tabControl = ttk.Notebook(self.win) # Create Tab Control tab1 = ttk.Frame(tabControl) # Create a tab tabControl.add(tab1, text='MySQL') # Add the tab tab2 = ttk.Frame(tabControl) # Add a second tab tabControl.add(tab2, text='Widgets') # Make second tab visible tabControl.pack(expand=1, fill="both") # Pack to make visible # ~ Tab Control introduced here ----------------------------------------- # We are creating a container frame to hold all other widgets self.mySQL = ttk.LabelFrame(tab1, text=' Python Database ') self.mySQL.grid(column=0, row=0, padx=8, pady=4) # Creating a Label ttk.Label(self.mySQL, text="Book Title:").grid(column=0, row=0, sticky='W') # Adding a Textbox Entry widget book = tk.StringVar() self.bookTitle = ttk.Entry(self.mySQL, width=34, textvariable=book) self.bookTitle.grid(column=0, row=1, sticky='W') # Adding a Textbox Entry widget book1 = tk.StringVar() self.bookTitle1 = ttk.Entry(self.mySQL, width=34, textvariable=book1) self.bookTitle1.grid(column=0, row=2, sticky='W') # Adding a Textbox Entry widget book2 = tk.StringVar() self.bookTitle2 = ttk.Entry(self.mySQL, width=34, textvariable=book2) self.bookTitle2.grid(column=0, row=3, sticky='W') # Creating a Label ttk.Label(self.mySQL, text="Page:").grid(column=1, row=0, sticky='W') # Adding a Textbox Entry widget page = tk.StringVar() self.pageNumber = ttk.Entry(self.mySQL, width=6, textvariable=page) self.pageNumber.grid(column=1, row=1, sticky='W') # Adding a Textbox Entry widget page = tk.StringVar() self.pageNumber1 = ttk.Entry(self.mySQL, width=6, textvariable=page) self.pageNumber1.grid(column=1, row=2, sticky='W') # Adding a Textbox Entry widget page = tk.StringVar() self.pageNumber2 = ttk.Entry(self.mySQL, width=6, textvariable=page) self.pageNumber2.grid(column=1, row=3, sticky='W') # Adding a Button self.action = ttk.Button(self.mySQL, text="Insert Quote", command=self.insertQuote) self.action.grid(column=2, row=1) # Adding a Button self.action1 = ttk.Button(self.mySQL, text="Get Quotes", command=self.getQuote) self.action1.grid(column=2, row=2) # Adding a Button self.action2 = ttk.Button(self.mySQL, text="Mody Quote", command=self.modifyQuote) self.action2.grid(column=2, row=3) # Add some space around each widget for child in self.mySQL.winfo_children(): child.grid_configure(padx=2, pady=4) quoteFrame = ttk.LabelFrame(tab1, text=' Book Quotation ') quoteFrame.grid(column=0, row=1, padx=8, pady=4) # Using a scrolled Text control quoteW = 40; quoteH = 6 self.quote = scrolledtext.ScrolledText(quoteFrame, width=quoteW, height=quoteH, wrap=tk.WORD) self.quote.grid(column=0, row=8, sticky='WE', columnspan=3) # Add some space around each widget for child in quoteFrame.winfo_children(): child.grid_configure(padx=2, pady=4) #====================================================================================================== # Tab Control 2 #====================================================================================================== # We are creating a container frame to hold all other widgets -- Tab2 self.mySQL2 = ttk.LabelFrame(tab2, text=WIDGET_LABEL) self.mySQL2.grid(column=0, row=0, padx=8, pady=4) # Creating three checkbuttons self.chVarDis = tk.IntVar() self.check1 = tk.Checkbutton(self.mySQL2, text="Disabled", variable=self.chVarDis, state='disabled') self.check1.select() self.check1.grid(column=0, row=0, sticky=tk.W) self.chVarUn = tk.IntVar() self.check2 = tk.Checkbutton(self.mySQL2, text="UnChecked", variable=self.chVarUn) self.check2.deselect() self.check2.grid(column=1, row=0, sticky=tk.W ) self.chVarEn = tk.IntVar() self.check3 = tk.Checkbutton(self.mySQL2, text="Toggle", variable=self.chVarEn) self.check3.deselect() self.check3.grid(column=2, row=0, sticky=tk.W) # trace the state of the two checkbuttons self.chVarUn.trace('w', lambda unused0, unused1, unused2 : self.checkCallback()) self.chVarEn.trace('w', lambda unused0, unused1, unused2 : self.checkCallback()) # Radiobutton list colors = ["Blue", "Gold", "Red"] self.radVar = tk.IntVar() # Selecting a non-existing index value for radVar self.radVar.set(99) # Creating all three Radiobutton widgets within one loop for col in range(3): curRad = 'rad' + str(col) curRad = tk.Radiobutton(self.mySQL2, text=colors[col], variable=self.radVar, value=col, command=self.radCall) curRad.grid(column=col, row=6, sticky=tk.W, columnspan=3) # And now adding tooltips tt.createToolTip(curRad, 'This is a Radiobutton control.') # Create a container to hold labels labelsFrame = ttk.LabelFrame(self.mySQL2, text=' Labels within a Frame ') labelsFrame.grid(column=0, row=7, pady=6) # Place labels into the container element - vertically ttk.Label(labelsFrame, text="Choose a number:").grid(column=0, row=0) ttk.Label(labelsFrame, text="Label 2").grid(column=0, row=1) # Add some space around each label for child in labelsFrame.winfo_children(): child.grid_configure(padx=6, pady=1) number = tk.StringVar() self.combo = ttk.Combobox(self.mySQL2, width=12, textvariable=number) self.combo['values'] = (1, 2, 4, 42, 100) self.combo.grid(column=1, row=7, sticky=tk.W) self.combo.current(0) self.combo.bind('<<ComboboxSelected>>', self._combo) # Adding a Spinbox widget using a set of values self.spin = Spinbox(self.mySQL2, values=(1, 2, 4, 42, 100), width=5, bd=8, command=self._spin) self.spin.grid(column=2, row=7, sticky='W,', padx=6, pady=1) # Using a scrolled Text control scrolW = 40; scrolH = 1 self.scr = scrolledtext.ScrolledText(self.mySQL2, width=scrolW, height=scrolH, wrap=tk.WORD) self.scr.grid(column=0, row=8, sticky='WE', columnspan=3) # Create Manage Files Frame ------------------------------------------------ mngFilesFrame = ttk.LabelFrame(tab2, text=' Manage Files: ') mngFilesFrame.grid(column=0, row=1, sticky='WE', padx=10, pady=5) # Button Callback def getFileName(): print('hello from getFileName') fDir = path.dirname(__file__) fName = fd.askopenfilename(parent=self.win, initialdir=fDir) print(fName) self.fileEntry.config(state='enabled') self.fileEntry.delete(0, tk.END) self.fileEntry.insert(0, fName) if len(fName) > self.entryLen: self.fileEntry.config(width=len(fName) + 3) # Add Widgets to Manage Files Frame lb = ttk.Button(mngFilesFrame, text="Browse to File...", command=getFileName) lb.grid(column=0, row=0, sticky=tk.W) #----------------------------------------------------- file = tk.StringVar() self.entryLen = scrolW - 4 self.fileEntry = ttk.Entry(mngFilesFrame, width=self.entryLen, textvariable=file) self.fileEntry.grid(column=1, row=0, sticky=tk.W) #----------------------------------------------------- logDir = tk.StringVar() self.netwEntry = ttk.Entry(mngFilesFrame, width=self.entryLen, textvariable=logDir) self.netwEntry.grid(column=1, row=1, sticky=tk.W) def copyFile(): import shutil src = self.fileEntry.get() file = src.split('/')[-1] dst = self.netwEntry.get() + '\\'+ file try: shutil.copy(src, dst) mBox.showinfo('Copy File to Network', 'Succes: File copied.') except FileNotFoundError as err: mBox.showerror('Copy File to Network', '*** Failed to copy file! ***\n\n' + str(err)) except Exception as ex: mBox.showerror('Copy File to Network', '*** Failed to copy file! ***\n\n' + str(ex)) cb = ttk.Button(mngFilesFrame, text="Copy File To : ", command=copyFile) cb.grid(column=0, row=1, sticky=tk.E) # Add some space around each label for child in mngFilesFrame.winfo_children(): child.grid_configure(padx=6, pady=6) # Creating a Menu Bar ========================================================== menuBar = Menu(tab1) self.win.config(menu=menuBar) # Add menu items fileMenu = Menu(menuBar, tearoff=0) fileMenu.add_command(label="New") fileMenu.add_separator() fileMenu.add_command(label="Exit", command=self._quit) menuBar.add_cascade(label="File", menu=fileMenu) # Add another Menu to the Menu Bar and an item helpMenu = Menu(menuBar, tearoff=0) helpMenu.add_command(label="About") menuBar.add_cascade(label="Help", menu=helpMenu) # Change the main windows icon self.win.iconbitmap(r'C:\Python34\DLLs\pyc.ico') # Using tkinter Variable Classes strData = tk.StringVar() strData.set('Hello StringVar') # It is not necessary to create a tk.StringVar() strData = tk.StringVar() strData = self.spin.get() # Place cursor into name Entry self.bookTitle.focus() # Add a Tooltip to the Spinbox tt.createToolTip(self.spin, 'This is a Spin control.') # Add Tooltips to more widgets tt.createToolTip(self.bookTitle, 'This is an Entry control.') tt.createToolTip(self.action, 'This is a Button control.') tt.createToolTip(self.scr, 'This is a ScrolledText control.')
def createWidgets(self): # Adding tabs self.tabControl = ttk.Notebook(self.win) self.tab1 = ttk.Frame(self.tabControl) self.tabControl.add(self.tab1, text='Tab 1') self.tabControl.pack(expand=1, fill="both") self.tab2 = ttk.Frame(self.tabControl) self.tabControl.add(self.tab2, text='Tab 2') # Creating a container frame to hold all other widgets self.monty = ttk.LabelFrame(self.tab1, text=' Monty Python ') self.monty.grid(column=0, row=0, padx=8, pady=4) # Second label for second tab self.monty2 = ttk.LabelFrame(self.tab2, text=' The Snake ') self.monty2.grid(column=0, row=0, padx=8, pady=4) # win.resizable(0,0) # Adding a label self.aLabel = ttk.Label(self.monty, text="A label") self.aLabel.grid(column=0, row=0) # Adding a button self.action = ttk.Button(self.monty, text="Click Me!", command=self.clickMe) # Position button in second row, second column (zero-based) self.action.grid(column=2, row=1) # Changing label ttk.Label(self.monty, text="Enter a name:").grid(column=0, row=0, sticky='W') # Adding a textbox entry widget self.name = tk.StringVar() self.nameEntered = ttk.Entry(self.monty, width=24, textvariable=self.name) self.nameEntered.grid(column=0, row=1, sticky=tk.W) self.nameEntered.delete(0, tk.END) self.nameEntered.insert(0, '< default name>') # Place cursor into name Entry #self.nameEntered.focus() self.tabControl.select(1) # Adding combo box widgets ttk.Label(self.monty, text="Choose a number: ").grid(column=1, row=0) self.number = tk.StringVar() self.numberChosen = ttk.Combobox(self.monty, width=14, textvariable=self.number, state='readonly') self.numberChosen['values'] = (1, 2, 4, 42, 100) self.numberChosen.grid(column=1, row=1) self.numberChosen.current(0) # Creating three checkbuttons self.chVarDis = tk.IntVar() self.check1 = tk.Checkbutton(self.monty2, text="Disabled", variable=self.chVarDis, state='disabled') self.check1.select() self.check1.grid(column=0, row=4, sticky=tk.W) self.chVarUn = tk.IntVar() self.check2 = tk.Checkbutton(self.monty2, text="UnChecked", variable=self.chVarUn) self.check2.deselect() self.check2.grid(column=1, row=4, sticky=tk.W) self.chVarEn = tk.IntVar() self.check3 = tk.Checkbutton(self.monty2, text="Enabled", variable=self.chVarEn) self.check3.select() self.check3.grid(column=2, row=4, sticky=tk.W) # Adding Radio buttons self.colors = ["Blue", "Gold", "Red"] # create three radiobuttons self.radVar = tk.IntVar() # Select non-existing index for radVar self.radVar.set(99) # Create three radiobutton widgets with a loop for col in range(3): curRad = 'rad' + str(col) curRad = tk.Radiobutton(self.monty2, text=self.colors[col], variable=self.radVar, value=col, command=self.radCall) curRad.grid(column=col, row=5, sticky=tk.W) # Adding a Spinbox widget # spin = Spinbox(monty, from_=0, to=10, width=5, bd=8, command=_spin) # Adding a Spinbox widget using a set of values self.spin = Spinbox(self.monty, values=(1, 2, 4, 42, 100), width=5, bd=8, command=self._spin) self.spin.grid(column=0, row=2) # Adding a second Spinbox widget self.spin2 = Spinbox(self.monty, values=(0, 50, 100), width=5, bd=8, relief=tk.RAISED, command=self._spin) self.spin2.grid(column=1, row=2) # Using a sccrolled text control self.scrolW = 40 self.scrolH = 10 self.scr = scrolledtext.ScrolledText(self.monty, width=self.scrolW, height=self.scrolH, wrap=tk.WORD) self.scr.grid(column=0, row=3, sticky='W', columnspan=3) # Create a container to hold labels self.labelsFrame = ttk.LabelFrame(self.monty2, text=' Labels in a Frame ') self.labelsFrame.grid(column=0, row=7, padx=20, pady=40) # Place labels into the container element ttk.Label(self.labelsFrame, text="Label1").grid(column=0, row=0) ttk.Label(self.labelsFrame, text="Label2").grid(column=0, row=1) ttk.Label(self.labelsFrame, text="Label3").grid(column=0, row=2) # Add space around labels inside labelFrame for child in self.labelsFrame.winfo_children(): child.grid_configure(padx=8, pady=4) # Place cursor into name Entry self.nameEntered.focus() # Create a menu self.menuBar = Menu(self.win) self.win.config(menu=self.menuBar) self.fileMenu = Menu(self.menuBar, tearoff=0) self.fileMenu.add_command(label="New") self.fileMenu.add_separator() self.fileMenu.add_command(label="Exit", command=self._quit) self.menuBar.add_cascade(label="File", menu=self.fileMenu) self.helpMenu = Menu(self.menuBar, tearoff=0) self.helpMenu.add_command(label="About", command=self._msgBox) self.menuBar.add_cascade(label="Help", menu=self.helpMenu) # Change the main windows icon # win.iconbitmap(r'/usr/bin/python3/icon/path') # Add a tooltip tt.createToolTip(self.spin, 'This is a Spin control.') # Add tooltips for more widgets tt.createToolTip(self.nameEntered, 'This is an entry control.') tt.createToolTip(self.action, 'This is a button control.') tt.createToolTip(self.scr, 'This is a scrolled text control.') ################################################################### # Create Manage Files Frame mngFilesFrame = ttk.LabelFrame(self.tab2, text='Manage Files: ') mngFilesFrame.grid(column=0, row=1, sticky='WE', padx=10, pady=5) # Button Callback def getFilename(): print('hello from getFileName') fDir = path.dirname(__file__) fName = fd.askopenfilename(parent=self.win, initialdir=fDir) # Add widgets to manage files frame lb = ttk.Button(mngFilesFrame, text="Browse to File...", command=getFilename) lb.grid(column=0, row=0, sticky=tk.W) file = tk.StringVar() self.entryLen = self.scrolW self.fileEntry = ttk.Entry(mngFilesFrame, width=self.entryLen, textvariable=file) self.fileEntry.grid(column=1, row=0, sticky=tk.W) logDir = tk.StringVar() self.netwEntry =ttk.Entry(mngFilesFrame, width=self.entryLen, textvariable=logDir) self.netwEntry.grid(column=1, row=1, sticky=tk.W) def copyFile(): import shutil src = self.fileEntry.get() file = src.split('/')[-1] dest = self.netwEntry.get() + '\\' + file try: shutil.copy(src, dest) mBox.showinfo('Copy File to Network', 'Success: File copied.') except FileNotFoundError as err: mBox.showerror('Copy File to Network', '*** Failed to copy file! **\n\n' + str(err)) except Exception as ex: mBox.showerror('Copy File to Network', '*** Failed to copy file! **\n\n' + str(ex)) cb = ttk.Button(mngFilesFrame, text="Copy File to: ", command=copyFile) cb.grid(column=0, row=1, sticky=tk.E) # Add some space around each label for child in mngFilesFrame.winfo_children(): child.grid_configure(padx=6, pady=6)
up.grid(column=2, row=5, sticky=W) ttk.Label(mainframe, text="Lower").grid(column=1, row=6, sticky=W) co = ttk.Combobox(mainframe, textvariable=co) co['values'] = gnc.COLONS co['state'] = 'readonly' co.grid(column=2, row=6, sticky=W) ttk.Label(mainframe, text="Anal").grid(column=1, row=7, sticky=W) ba = ttk.Combobox(mainframe, textvariable=ba) ba['values'] = gnc.BANDING ba['state'] = 'readonly' ba.grid(column=2, row=7, sticky=W) ttk.Label(mainframe, text="Clips").grid(column=1, row=8, sticky=W) s = Spinbox(mainframe, from_=0, to=20, textvariable=cl) s.grid(column=2, row=8, sticky=W) ttk.Label(mainframe, text="Consult").grid(column=1, row=9, sticky=W) con = ttk.Combobox(mainframe, textvariable=con) con['values'] = gnc.CONSULT_LIST con['state'] = 'readonly' con.grid(column=2, row=9, sticky=W) ttk.Label(mainframe, text="Message").grid(column=1, row=10, sticky=W) ttk.Entry(mainframe, textvariable=mes).grid(column=2, row=10, sticky=W) ttk.Label(mainframe, text="Time").grid(column=1, row=11, sticky=W) ti = Spinbox(mainframe, from_=0, to=90, textvariable=ot) ti.grid(column=2, row=11, sticky=W)
textvariable=number, state='readonly') number_chosen['values'] = (1, 2, 4, 42, 100) number_chosen.grid(column=1, row=1) number_chosen.current(0) # Spinbox callback def _spin(): value = spin.get() print(value) scrol.insert(tk.INSERT, value + '\n') # Adding a Spinbox widget spin = Spinbox(mighty, from_=0, to=10, width=5) spin.grid(column=0, row=2) # Using a scrolled Text control scrol_w = 30 scrol_h = 3 scrol = scrolledtext.ScrolledText(mighty, width=scrol_w, height=scrol_h, wrap=tk.WORD) scrol.grid(column=0, row=3, sticky='WE', columnspan=3) # Tab Control 2 refactoring --------------------------------------------------------- # We are creating a container frame to hold all other widgets -- Tab2 mighty2 = ttk.LabelFrame(tab2, text=' The Snake ') mighty2.grid(column=0, row=0, padx=8, pady=4)
def updategui(self, *args): if args[0] == True: print('Cleaning GUI') for item in self.labellist: item.grid_forget() for item in self.entrylist: item.grid_forget() for item in self.verifylist: item.grid_forget() for item in self.misclist: item.grid_forget() self.labellist = [] self.entrylist = [] self.verifylist = [] self.misclist = [] if self.curmode == self.optionDiscuss: self.newrowindex = 4 self.labelPermalink = Label(self, text="Thread Permalink:") self.entryPermalink = Entry(self) self.rowconfigure(2,weight=2) self.labelPermalink.grid(row=2,column=0) self.entryPermalink.grid(row=2,column=1) self.labelcrossposting = Label(self,text="Crosspost to:") self.labelcrossposting.grid(row=3,column=0,columnspan=2,sticky="w") for m in range(5): self.redditlabel = Label(self,text="/r/") self.redditlabel.grid(row=self.newrowindex,column=0, sticky="e") self.labellist.append(self.redditlabel) self.redditentry = Entry(self) self.redditentry.grid(row=self.newrowindex,column=1) self.entrylist.append(self.redditentry) self.newrowindex +=1 self.morerowbutton = Button(self,text="+row",command=lambda: self.morerows('/r/', 0, 1, 20)) self.morerowbutton.grid(row=898,column=0,columnspan=2) self.verifybutton = Button(self,text="Verify",command= lambda: self.updategui(False)) self.verifybutton.grid(row=899,column=0,columnspan=2) self.newrowindex += 2 self.misclist.append(self.labelPermalink) self.misclist.append(self.labelcrossposting) self.misclist.append(self.entryPermalink) self.misclist.append(self.morerowbutton) self.misclist.append(self.verifybutton) if self.curmode == self.optionRegister: self.newrowindex = 6 self.labelCanUsername = Label(self, text="Candidate's Username: /u/") self.entryCanUsername = Entry(self) self.labelCanRealname = Label(self, text="Candidate's Realname:") self.entryCanRealname = Entry(self) self.labelCanFlair = Label(self, text="Candidate's Flair:") self.entryCanFlair = Entry(self) self.entryMo = Spinbox(self, width=9, values=('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')) self.entryDa = Spinbox(self, width=2, from_=1, to=31) self.entryYr = Spinbox(self, width=4, from_=2014, to=2500) self.labelHH = Label(self, text="Schedule time UTC:") self.entryHH = Spinbox(self, from_=0, to=23, width=2) self.entryMM = Spinbox(self, from_=0, to=59, width=2) self.entryYr.delete(0,'end') self.entryYr.insert(0,2014) self.morerowbutton = Button(self,text="+question",command=lambda: self.morerows('Q:', 0, 1, 25)) self.morerowbutton.grid(row=898,column=0,columnspan=8) self.verifybutton = Button(self,text="Verify",command= lambda: self.updategui(False)) self.verifybutton.grid(row=899,column=0,columnspan=8) self.misclist.append(self.labelCanUsername) self.misclist.append(self.labelCanRealname) self.misclist.append(self.entryCanUsername) self.misclist.append(self.entryCanRealname) self.misclist.append(self.labelHH) self.misclist.append(self.entryHH) self.misclist.append(self.entryMM) self.misclist.append(self.entryMo) self.misclist.append(self.entryDa) self.misclist.append(self.entryYr) self.labelCanUsername.grid(row=2, column=0, sticky="e") self.labelCanRealname.grid(row=3, column=0, sticky="e") self.entryCanUsername.grid(row=2, column=1, columnspan=3) self.entryCanRealname.grid(row=3, column=1, columnspan=3) self.entryMo.grid(row=4, column=1,sticky="e") self.entryDa.grid(row=4, column=2) self.entryYr.grid(row=4, column=3) self.labelHH.grid(row=4, column=0, sticky="se", pady=5) self.entryHH.grid(row=5, column=1, sticky="e") self.entryMM.grid(row=5, column=2, sticky="w") else: if self.curmode == self.optionDiscuss: verifies = [] i = self.entryPermalink.get() if len(i) == 6: pid = i else: if 'www.reddit.com/r/' in i and '/comments/' in i: pid = i.split('/comments/')[1].split('/')[0] if 'http://redd.it/' in i: pid = i.split('redd.it/')[1] for flag in self.verifylist: flag.grid_forget() self.verifylist.remove(flag) try: print('Fetching Submission ' + pid) self.r.get_info(thing_id="t3_" + pid).title + 'Check' self.redditlabel = Label(self, image=self.indicatorGreen) self.redditlabel.grid(row=2,column=2) self.verifylist.append(self.redditlabel) verifies.append(True) print('\tSuccess') except: print('Failed. Make sure to include the http://. Copy and paste straight from your browser for best result') self.redditlabel = Label(self, image=self.indicatorRed) self.redditlabel.grid(row=2,column=2) self.verifylist.append(self.redditlabel) verifies.append(False) for entry in self.entrylist: i = entry.get() if i != '': print('Fetching /r/' + i) if all(char in string.ascii_letters+string.digits+'_-' for char in i): try: sub = self.r.get_subreddit(i,fetch=True) self.redditlabel = Label(self, image=self.indicatorGreen) self.redditlabel.grid(row=entry.grid_info()['row'],column=2) self.verifylist.append(self.redditlabel) verifies.append(True) print('\tSuccess') except: self.redditlabel = Label(self, image=self.indicatorRed) self.redditlabel.grid(row=entry.grid_info()['row'],column=2) self.verifylist.append(self.redditlabel) verifies.append(False) print('\tFailed') time.sleep(2) else: self.redditlabel = Label(self, image=self.indicatorRed) self.redditlabel.grid(row=entry.grid_info()['row'],column=2) self.verifylist.append(self.redditlabel) verifies.append(False) print('\tFailed') print(verifies) if self.curmode == self.optionRegister: verifies = [] u=self.entryCanUsername.get() print('Fetching /u/' + u) if not all(char in string.ascii_letters+string.digits+'_-' for char in u): self.redditlabel = Label(self, image=self.indicatorRed) self.redditlabel.grid(row=2, column=4) self.verifylist.append(self.redditlabel) verifies.append(False) print('\tBad characterage') else: try: u = self.r.get_redditor(u) print(u) self.redditlabel = Label(self, image=self.indicatorGreen) self.redditlabel.grid(row=2,column=4) self.verifylist.append(self.redditlabel) verifies.append(True) print('\tSuccess') except: self.redditlabel = Label(self, image=self.indicatorRed) self.redditlabel.grid(row=2,column=4) self.verifylist.append(self.redditlabel) verifies.append(False) print('\tFailed') try: print('Checking Time') t = self.entryMo.get() + ' ' + self.entryDa.get() + ' ' + self.entryYr.get() + ' ' + self.entryHH.get() + ':' + self.entryMM.get() plandate = datetime.datetime.strptime(t, "%B %d %Y %H:%M") plandate = datetime.datetime.utcfromtimestamp(plandate.timestamp()) print('\t' + str(plandate.timestamp())) self.redditlabel = Label(self, image=self.indicatorGreen) self.redditlabel.grid(row=5,column=3) self.verifylist.append(self.redditlabel) verifies.append(True) except: print('\tFailed') self.redditlabel = Label(self, image=self.indicatorRed) self.redditlabel.grid(row=5,column=3) self.verifylist.append(self.redditlabel) verifies.append(False) print(verifies)
def main(): parser = ConfigParser() parser.read("default.ini") logging.basicConfig(filename='history.log', filemode='w', format='%(asctime)s:%(name)s - %(levelname)s - %(' 'message)s') #looking whether the program is in debug mode or not if parser.get("default", "debug") == '1': logging.getLogger().setLevel(logging.DEBUG) if parser.get("default", "debug") == '0': logging.getLogger().setLevel(logging.INFO) #searching for all the available coms if sys.platform.startswith('win'): ports = ['COM%s' % (i + 1) for i in range(256)] serialPorts = [] for port in ports: try: s = serial.Serial(port) s.close() serialPorts.append(port) except (OSError, serial.SerialException): pass #creating GUI window = Tk() window.title(parser.get("default", "title")) window.geometry("300x150") #connecting to the com indicated in the "default.ini" try: com = str(parser.get("default", "port")) ser = serial.Serial(port=com, baudrate=int(parser.get("default", "baudrate")), timeout=0, writeTimeout=0) except (OSError, serial.SerialException): messagebox.showinfo(parser.get("default", "title"), "Could not open " + com) #creating the rest of the GUI window.protocol("WM_DELETE_WINDOW", lambda b=window: callback(b)) tab_control = ttk.Notebook(window) tab1 = ttk.Frame(tab_control) tab2 = ttk.Frame(tab_control) tab3 = ttk.Frame(tab_control) tab_control.add(tab1, text="Receive") tab_control.add(tab2, text="Ports") tab_control.add(tab3, text="Info") lbl1 = scrolledtext.ScrolledText(tab1, wrap="word") lbl1.grid(column=0, row=0) portsSpinbox = Spinbox(tab2, from_=0, to=256) portsSpinbox.grid(column=0, row=0) btn2 = Button( tab2, text="Set port", command=lambda a=com, b=portsSpinbox, c=parser: clicked3(a, b, c)) btn2.grid(column=1, row=0) label5 = Label(tab2, text="Port opened:" + com) label5.grid(column=0, row=3) btn3 = Button(tab2, text="Ports", command=lambda a=serialPorts, b=parser: clicked2(a, b)) btn3.grid(column=0, row=1) lbl3 = Label(tab3, text="Made by") lbl3.grid(column=0, row=0) lbl4 = Label(tab3, text="Federico Faggian, Giulio Tavera and Edoardo Tinaru") lbl4.grid(column=0, row=1) tab_control.pack(expand=1, fill='both') #check for the serial port and write the data if ser.isOpen(): window.after(100, lambda a=ser, b=window, c=lbl1: receive(a, b, c)) window.mainloop()
def fifth_window(root, info): s = ttk.Style() s.configure('nat.TFrame', background="white") fromdayvar = StringVar() frommonthvar = StringVar() fromyearvar = StringVar() todayvar = StringVar() tomonthvar = StringVar() toyearvar = StringVar() def back(info=info): info['fromdate'] = [int(fromyear.get()), (month_to_number( frommonth.get())), int(fromday.get())] info['todate'] = [int(toyear.get()), (month_to_number(tomonth.get())), int(today.get())] fourth_window(root=root, info=info) def info_completed(info=info): info['fromdate'] = [int(fromyear.get()), (month_to_number( frommonth.get())), int(fromday.get())] info['todate'] = [int(toyear.get()), (month_to_number(tomonth.get())), int(today.get())] pickle.dump(info, open('{home}/Desktop/natappy/pickle/info.pickle'.format(home=home), 'wb')) try: root.withdraw() print('info=', info) if not info['competition']: nat.create_report(info['bloggers'], info['platforms'], info['tags'], info['format'], info['fromdate'], info['todate'], info[ 'replies'], info['retweets'], info['excludetags'], info['brandname'], info['campaign'], info['blogpost']) root.withdraw() messagebox.showinfo("Report completed", 'Details: \n Report: {format} \n Media: {platform2} \n Tags: {tags2} \n Bloggers: {bloggers2} \n Report completed'.format(tags2=' '.join( [tag for tag in info['tags']]), platform2=' '.join([platform for platform in info['platforms']]), bloggers2=' '.join([blogger for blogger in info['bloggers']]), **info), parent=c) else: campcomp.campaign_competition(info['blogpost'], info['comptags'], info['competition'], info['campaign'], info['brandname'], info['excludetags'], info[ 'bloggers'], info['tags'], info['format'], info['platforms'], info['fromdate'], info['todate'], info['replies'], info['retweets'], info['blogposts']) # comp.competreport(info['competition'],info['comptags'],info['fromdate'],info['bloggers'],info['todate'],info['settings'],info['format'],info['brandname'],info['campaign']) root.withdraw() messagebox.showinfo("Report completed", 'Details: \n Report: {format} \n Media: {platform2} \n Tags: {tags2} \n Bloggers: {bloggers2} \n Report completed'.format(tags2=' '.join( [tag for tag in info['tags']]), platform2=' '.join([platform for platform in info['platforms']]), bloggers2=' '.join([blogger for blogger in info['bloggers']]), **info), parent=c) except Exception as e: info = 'Exception: {e}'.format(e=e) print(info + '\nExiting now') messagebox.showinfo("Error", info) root.quit() def month_to_number(month): return int({'January': '01', 'February': '02', 'March': '03', 'April': '04', 'May': '05', 'June': '06', 'July': '07', 'August': '08', 'September': '09', 'October': 10, 'November': 11, 'December': 12}[month]) c = ttk.Frame(root, style='nat.TFrame') c.grid(column=0, row=0, sticky=(N, W, E, S)) background_image = tkinter.PhotoImage(file='%s/Desktop/natappy/images/palms.gif' % home) background_label = tkinter.Label(c, image=background_image) background_label.image = background_image background_label.place(x=0, y=0, relwidth=1, relheight=1) root.grid_columnconfigure(0, weight=3) root.grid_rowconfigure(0, weight=3) fromlbl = ttk.Label(c, text="From:", anchor=E, width=0) fromlbl.grid(column=0, row=0, padx=20, pady=(20, 4), sticky=(N, W, S, E)) tolbl = ttk.Label(c, text="To:", anchor=E, width=0) tolbl.grid(column=0, row=2, padx=20, pady=(20, 4), sticky=(N, W, S, E)) fromday = Spinbox(c, values=[i for i in range(1, 32)], width=5, textvariable=fromdayvar) fromday.grid(column=0, row=1, sticky=W, padx=(20, 10), pady=0) frommonth = Spinbox(c, values=['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], textvariable=frommonthvar, width=11) frommonth.grid(column=1, row=1, sticky=W, padx=(10, 20), pady=0) fromyear = Spinbox(c, values=[2014, 2015, 2016], width=5, textvariable=fromyearvar) fromyear.grid(column=2, row=1, sticky=W, padx=(20, 20), pady=0) today = Spinbox(c, values=[i for i in range(1, 32)], width=5, textvariable=todayvar) today.grid(column=0, row=3, sticky=W, padx=(20, 10), pady=0) tomonth = Spinbox(c, values=['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], width=11, textvariable=tomonthvar) tomonth.grid(column=1, row=3, sticky=W, padx=(10, 20), pady=0) toyear = Spinbox(c, values=[2014, 2015, 2016], width=5, textvariable=toyearvar) toyear.grid(column=2, row=3, sticky=W, padx=(20, 20), pady=0) send = ttk.Button(c, text='Create Report', command=info_completed, default='active') send.grid(column=3, row=6, pady=20, sticky=E, padx=(2, 20)) close = ttk.Button(c, text='Back', command=back, default='active') close.grid(column=2, row=6, pady=20, sticky=E) c.grid_columnconfigure(0, weight=1) c.grid_rowconfigure(5, weight=1) if info['fromdate']: if len(str(info['fromdate'][1])) == 1: month = '0' + str(info['fromdate'][1]) else: month = str(info['fromdate'][1]) fromdayvar.set(info['fromdate'][2]) frommonthvar.set(number_to_month(month)) fromyearvar.set(info['fromdate'][0]) else: fromdayvar.set((date.today() - timedelta(days=7)).day) if len(str((date.today() - timedelta(days=7)).month)) == 1: month = '0' + (str((date.today() - timedelta(days=7)).month)) else: month = (str((date.today() - timedelta(days=7)).month)) frommonthvar.set(number_to_month(month)) fromyearvar.set((date.today() - timedelta(days=7)).year) if info['todate']: if len(str(info['todate'][1])) == 1: month = '0' + str(info['todate'][1]) else: month = str(info['todate'][1]) todayvar.set(info['todate'][2]) tomonthvar.set(number_to_month(month)) toyearvar.set(info['todate'][0]) else: todayvar.set(datetime.datetime.now().day) if len(str(datetime.datetime.now().month)) == 1: month = '0' + str(datetime.datetime.now().month) else: month = str(datetime.datetime.now().month) tomonthvar.set(number_to_month(month)) toyearvar.set(datetime.datetime.now().year) root.title('5/5 Date Range') root.geometry('550x400+440+200')
def __init__(self,master=None): Frame.__init__(self,master) #Sides of Dice labelSides=Label(self,text="Sides") labelSides.grid(row=0,column=0) self.sides=StringVar() self.sides.set(20) spinboxSides=Spinbox(self,from_=1,to=20,increment=1,width=4) spinboxSides.config(textvariable=self.sides, font="sans 24", justify="center") spinboxSides.grid(row=0,column=1) #Number of Dices labelNumber=Label(self,text="Number") labelNumber.grid(row=1,column=0) self.number=StringVar() self.number.set(1) spinboxNumber=Spinbox(self,from_=1,to=30,increment=1,width=4) spinboxNumber.config(textvariable=self.number, font="sans 24", justify="center") spinboxNumber.grid(row=1,column=1) #Modifier labelModifier=Label(self,text="Modifier") labelModifier.grid(row=2,column=0) self.modifier=StringVar() self.modifier.set(0) spinboxModifier=Spinbox(self,from_=-5,to=5,increment=1,width=4) spinboxModifier.config(textvariable=self.modifier, font="sans 24", justify="center") spinboxModifier.grid(row=2,column=1) #Hide Checkbox labelHide=Label(self, text="Hide") labelHide.grid(row=2, column=2) self.hide=IntVar() self.hide.set(0) checkbuttonHide=Checkbutton(self,variable=self.hide) checkbuttonHide.grid(row=2,column=3) #Result display self.result=StringVar() self.result.set("") labelResult1=Label(self,text="Result") labelResult1.grid(row=1, column=4) labelResult2=Label(self,text=self.result.get(),relief=SUNKEN,width=4) labelResult2.grid(row=1,column=5) #Button to roll buttonRoll=Button(self,text="Roll!", command=self.roll) buttonRoll.grid(row=2,column=5)