Python Tkinter.Label() Examples
The following are 30
code examples of Tkinter.Label().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
Tkinter
, or try the search function
.
Example #1
Source File: annotation_gui.py From SEM with MIT License | 9 votes |
def preferences(self, event=None): preferenceTop = tkinter.Toplevel() preferenceTop.focus_set() notebook = ttk.Notebook(preferenceTop) frame1 = ttk.Frame(notebook) notebook.add(frame1, text='general') frame2 = ttk.Frame(notebook) notebook.add(frame2, text='shortcuts') c = ttk.Checkbutton(frame1, text="Match whole word when broadcasting annotation", variable=self._whole_word) c.pack() shortcuts_vars = [] shortcuts_gui = [] cur_row = 0 j = -1 frame_list = [] frame_list.append(ttk.LabelFrame(frame2, text="common shortcuts")) frame_list[-1].pack(fill="both", expand="yes") for i, shortcut in enumerate(self.shortcuts): j += 1 key, cmd, bindings = shortcut name, command = cmd shortcuts_vars.append(tkinter.StringVar(frame_list[-1], value=key)) tkinter.Label(frame_list[-1], text=name).grid(row=cur_row, column=0, sticky=tkinter.W) entry = tkinter.Entry(frame_list[-1], textvariable=shortcuts_vars[j]) entry.grid(row=cur_row, column=1) cur_row += 1 notebook.pack() # # ? menu methods #
Example #2
Source File: components.py From SEM with MIT License | 8 votes |
def __init__(self, root, resource_dir): ttk.Frame.__init__(self, root) self.master_selector = None self.resource_dir = resource_dir self.items = os.listdir(os.path.join(self.resource_dir, "master")) self.cur_lang = tkinter.StringVar() self.select_lang_label = ttk.Label(root, text=u"select language:") self.langs = ttk.Combobox(root, textvariable=self.cur_lang) self.langs["values"] = self.items self.langs.current(0) for i, item in enumerate(self.items): if item == "fr": self.langs.current(i) self.langs.bind("<<ComboboxSelected>>", self.select_lang)
Example #3
Source File: viewer.py From networkx_viewer with GNU General Public License v3.0 | 7 votes |
def __init__(self, main_window, msg='Please enter a node:'): tk.Toplevel.__init__(self) self.main_window = main_window self.title('Node Entry') self.geometry('170x160') self.rowconfigure(3, weight=1) tk.Label(self, text=msg).grid(row=0, column=0, columnspan=2, sticky='NESW',padx=5,pady=5) self.posibilities = [d['dataG_id'] for n,d in main_window.canvas.dispG.nodes_iter(data=True)] self.entry = AutocompleteEntry(self.posibilities, self) self.entry.bind('<Return>', lambda e: self.destroy(), add='+') self.entry.grid(row=1, column=0, columnspan=2, sticky='NESW',padx=5,pady=5) tk.Button(self, text='Ok', command=self.destroy).grid( row=3, column=0, sticky='ESW',padx=5,pady=5) tk.Button(self, text='Cancel', command=self.cancel).grid( row=3, column=1, sticky='ESW',padx=5,pady=5) # Make modal self.winfo_toplevel().wait_window(self)
Example #4
Source File: fisheye.py From DualFisheye with MIT License | 7 votes |
def _make_slider(self, parent, rowidx, label, inival, maxval, res=0.5): # Create shared variable and set initial value. tkvar = tk.DoubleVar() tkvar.set(inival) # Set a callback for whenever tkvar is changed. # (The 'command' callback on the SpinBox only applies to the buttons.) tkvar.trace('w', self._update_callback) # Create the Label, SpinBox, and Scale objects. label = tk.Label(parent, text=label) spbox = tk.Spinbox(parent, textvariable=tkvar, from_=0, to=maxval, increment=res) slide = tk.Scale(parent, orient=tk.HORIZONTAL, showvalue=0, variable=tkvar, from_=0, to=maxval, resolution=res) label.grid(row=rowidx, column=0) spbox.grid(row=rowidx, column=1) slide.grid(row=rowidx, column=2) return tkvar # Find the largest output size that fits within the given bounds and # matches the aspect ratio of the original source image.
Example #5
Source File: test_geometry_managers.py From oss-ftp with MIT License | 6 votes |
def test_grid_slaves(self): self.assertEqual(self.root.grid_slaves(), []) a = tkinter.Label(self.root) a.grid_configure(row=0, column=1) b = tkinter.Label(self.root) b.grid_configure(row=1, column=0) c = tkinter.Label(self.root) c.grid_configure(row=1, column=1) d = tkinter.Label(self.root) d.grid_configure(row=1, column=1) self.assertEqual(self.root.grid_slaves(), [d, c, b, a]) self.assertEqual(self.root.grid_slaves(row=0), [a]) self.assertEqual(self.root.grid_slaves(row=1), [d, c, b]) self.assertEqual(self.root.grid_slaves(column=0), [b]) self.assertEqual(self.root.grid_slaves(column=1), [d, c, a]) self.assertEqual(self.root.grid_slaves(row=1, column=1), [d, c])
Example #6
Source File: enhancer.py From mxnet-lambda with Apache License 2.0 | 6 votes |
def __init__(self, master, image, name, enhancer, lo, hi): tkinter.Frame.__init__(self, master) # set up the image self.tkim = ImageTk.PhotoImage(image.mode, image.size) self.enhancer = enhancer(image) self.update("1.0") # normalize # image window tkinter.Label(self, image=self.tkim).pack() # scale s = tkinter.Scale(self, label=name, orient=tkinter.HORIZONTAL, from_=lo, to=hi, resolution=0.01, command=self.update) s.set(self.value) s.pack()
Example #7
Source File: __init__.py From 3DGCN with MIT License | 6 votes |
def ShowMol(mol, size=(300, 300), kekulize=True, wedgeBonds=True, title='RDKit Molecule', **kwargs): """ Generates a picture of a molecule and displays it in a Tkinter window """ global tkRoot, tkLabel, tkPI try: import Tkinter except ImportError: import tkinter as Tkinter try: import ImageTk except ImportError: from PIL import ImageTk img = MolToImage(mol, size, kekulize, wedgeBonds, **kwargs) if not tkRoot: tkRoot = Tkinter.Tk() tkRoot.title(title) tkPI = ImageTk.PhotoImage(img) tkLabel = Tkinter.Label(tkRoot, image=tkPI) tkLabel.place(x=0, y=0, width=img.size[0], height=img.size[1]) else: tkPI.paste(img) tkRoot.geometry('%dx%d' % (img.size))
Example #8
Source File: Emotion Recognition.py From Emotion-Recognition-Using-SVMs with MIT License | 6 votes |
def updateImageCount(happyCount, sadCount): global HCount, SCount, imageCountString, countString # Updating only when called by smileCallback/noSmileCallback if happyCount is True and HCount < 400: HCount += 1 if sadCount is True and SCount < 400: SCount += 1 if HCount == 400 or SCount == 400: HCount = 0 SCount = 0 # --- Updating Labels # -- Main Count imageCountPercentage = str(float((trainer.index + 1) * 0.25)) \ if trainer.index+1 < len(faces.images) else "Classification DONE! 100" imageCountString = "Image Index: " + str(trainer.index+1) + "/400 " + "[" + imageCountPercentage + " %]" labelVar.set(imageCountString) # Updating the Label (ImageCount) # -- Individual Counts countString = "(Happy: " + str(HCount) + " " + "Sad: " + str(SCount) + ")\n" countVar.set(countString)
Example #9
Source File: btcrseed.py From btcrecover with GNU General Public License v2.0 | 6 votes |
def show_mnemonic_gui(mnemonic_sentence): """may be called *after* main() to display the successful result iff the GUI is in use :param mnemonic_sentence: the mnemonic sentence that was found :type mnemonic_sentence: unicode :rtype: None """ assert tk_root global pause_at_exit padding = 6 tk.Label(text="WARNING: seed information is sensitive, carefully protect it and do not share", fg="red") \ .pack(padx=padding, pady=padding) tk.Label(text="Seed found:").pack(side=tk.LEFT, padx=padding, pady=padding) entry = tk.Entry(width=80, readonlybackground="white") entry.insert(0, mnemonic_sentence) entry.config(state="readonly") entry.select_range(0, tk.END) entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=padding, pady=padding) tk_root.deiconify() tk_root.lift() entry.focus_set() tk_root.mainloop() # blocks until the user closes the window pause_at_exit = False
Example #10
Source File: steam-idle.py From idle_master_py with GNU General Public License v2.0 | 6 votes |
def init_gui(str_app_id): gui = tk.Tk() gui.title('App ' + str_app_id) gui.resizable(0,0) try: url = "http://cdn.akamai.steamstatic.com/steam/apps/" + str_app_id + "/header_292x136.jpg" image_bytes = urlopen(url).read() data_stream = io.BytesIO(image_bytes) pil_image = Image.open(data_stream) tk_image = ImageTk.PhotoImage(pil_image) label = tk.Label(gui, image=tk_image) label.image = tk_image except: label = tk.Label(gui, text="Couldn't load image") label.pack() return gui
Example #11
Source File: player.py From mxnet-lambda with Apache License 2.0 | 6 votes |
def __init__(self, master, im): if isinstance(im, list): # list of images self.im = im[1:] im = self.im[0] else: # sequence self.im = im if im.mode == "1": self.image = ImageTk.BitmapImage(im, foreground="white") else: self.image = ImageTk.PhotoImage(im) tkinter.Label.__init__(self, master, image=self.image, bg="black", bd=0) self.update() duration = im.info.get("duration", 100) self.after(duration, self.next)
Example #12
Source File: ImageTk.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _show(image, title): """Helper for the Image.show method.""" class UI(tkinter.Label): def __init__(self, master, im): if im.mode == "1": self.image = BitmapImage(im, foreground="white", master=master) else: self.image = PhotoImage(im, master=master) tkinter.Label.__init__(self, master, image=self.image, bg="black", bd=0) if not tkinter._default_root: raise IOError("tkinter not initialized") top = tkinter.Toplevel() if title: top.title(title) UI(top, image).pack()
Example #13
Source File: Torrent_ip_checker.py From FunUtils with MIT License | 6 votes |
def work(IP): conn = httplib.HTTPConnection("www.iknowwhatyoudownload.com/en/peer/?ip="+IP) conn.request("GET","/") response = conn.getresponse() data =response.read() soup = BS(data,"html.parser") table = soup.find('tbody') rows = table.findAll('tr') for tr in rows: cols = tr.findAll('td') Begin,End,Category,title,size=[c.text for c in cols] RESULT+="\n"+Begin+" "+Category+" "+title+" "+size toplevel = Toplevel() label= Label(toplevel,text=RESULT,height=0,width=100) label.pack() print RESULT
Example #14
Source File: gui_widgets.py From SVPV with MIT License | 6 votes |
def __init__(self, parent): tk.LabelFrame.__init__(self, parent) self.title = tk.Label(self, text='SV Length') self.len_GT_On = tk.IntVar(value=0) self.len_GT_On_CB = tk.Checkbutton(self, text=">", justify=tk.LEFT, variable=self.len_GT_On) self.len_GT_val = tk.Spinbox(self, values=(1,5,10,50,100,500), width=3) self.len_GT_Units = tk.Spinbox(self, values=("bp", "kbp", "Mbp"), width=3) self.len_LT_On = tk.IntVar(value=0) self.len_LT_On_CB = tk.Checkbutton(self, text="<", justify=tk.LEFT, variable=self.len_LT_On) self.len_LT_val = tk.Spinbox(self, values=(1,5,10,50,100,500), width=3) self.len_LT_Units = tk.Spinbox(self, values=("bp", "kbp", "Mbp"), width=3) self.title.grid(row=0, column=0, sticky=tk.EW, columnspan=4) self.len_GT_On_CB.grid(row=1, column=0, sticky=tk.EW) self.len_GT_val.grid(row=2, column=0, sticky=tk.EW) self.len_GT_Units.grid(row=2, column=1, sticky=tk.EW) self.len_LT_On_CB.grid(row=1, column=2, sticky=tk.EW) self.len_LT_val.grid(row=2, column=2, sticky=tk.EW) self.len_LT_Units.grid(row=2, column=3, sticky=tk.EW)
Example #15
Source File: agents.py From aima with MIT License | 6 votes |
def __init__(self, parent, env, canvas): super(EnvToolbar, self).__init__(parent, relief='raised', bd=2) # Initialize instance variables self.env = env self.canvas = canvas self.running = False self.speed = 1.0 # Create buttons and other controls for txt, cmd in [('Step >', self.env.step), ('Run >>', self.run), ('Stop [ ]', self.stop), ('List things', self.list_things), ('List agents', self.list_agents)]: tk.Button(self, text=txt, command=cmd).pack(side='left') tk.Label(self, text='Speed').pack(side='left') scale = tk.Scale(self, orient='h', from_=(1.0), to=10.0, resolution=1.0, command=self.set_speed) scale.set(self.speed) scale.pack(side='left')
Example #16
Source File: components.py From SEM with MIT License | 6 votes |
def __init__(self, root, main_window, button_opt): ttk.Frame.__init__(self, root) self.root = root self.main_window = main_window self.current_files = None self.button_opt = button_opt # define options for opening or saving a file self.file_opt = options = {} options['defaultextension'] = '.txt' options['filetypes'] = [('all files', '.*'), ('text files', '.txt')] options['initialdir'] = os.path.expanduser("~") options['parent'] = root options['title'] = 'Select files to annotate.' self.file_selector_button = ttk.Button(self.root, text=u"select file(s)", command=self.filenames) self.label = ttk.Label(self.root, text=u"selected file(s):") self.fa_search = tkinter.PhotoImage(file=os.path.join(self.main_window.resource_dir, "images", "fa_search_24_24.gif")) self.file_selector_button.config(image=self.fa_search, compound=tkinter.LEFT) self.scrollbar = ttk.Scrollbar(self.root) self.selected_files = tkinter.Listbox(self.root, yscrollcommand=self.scrollbar.set) self.scrollbar.config(command=self.selected_files.yview)
Example #17
Source File: ImageTk.py From teleport with Apache License 2.0 | 6 votes |
def _show(image, title): """Helper for the Image.show method.""" class UI(tkinter.Label): def __init__(self, master, im): if im.mode == "1": self.image = BitmapImage(im, foreground="white", master=master) else: self.image = PhotoImage(im, master=master) tkinter.Label.__init__(self, master, image=self.image, bg="black", bd=0) if not tkinter._default_root: raise IOError("tkinter not initialized") top = tkinter.Toplevel() if title: top.title(title) UI(top, image).pack()
Example #18
Source File: main.py From WxConn with MIT License | 6 votes |
def draw(self): self.title_canvas = tk.Canvas(self, bg=self.bgcolor, width=width, height=90, bd=0, highlightthickness=0, relief='ridge') self.title_pic = self._resize_ads_qrcode(RES_APP_TITLE, size=(260, 90)) self.title_canvas.create_image(0, 0, anchor='nw', image=self.title_pic) self.title_canvas.pack(padx=35, pady=15) self.qrcode = tk.Canvas(self, bg=self.bgcolor, width=200, height=200) #self.qrcode_pic = self._resize_ads_qrcode('qrcode.png', size=(200, 200)) #self.qrcode.create_image(0, 0, anchor='nw', image=self.qrcode_pic) self.qrcode.pack(pady=30) # 提示 self.lable_tip = tk.Label(self, text='请稍等', # 标签的文字 bg=self.bgcolor, # 背景颜色 font=('楷体',12), # 字体和字体大小 width=15, height=2 # 标签长宽 ) self.lable_tip.pack(pady=2,fill=tk.BOTH) # 固定窗口位置
Example #19
Source File: backend_tkagg.py From matplotlib-4-abaqus with MIT License | 6 votes |
def showtip(self, text): "Display text in tooltip window" self.text = text if self.tipwindow or not self.text: return x, y, _, _ = self.widget.bbox("insert") x = x + self.widget.winfo_rootx() + 27 y = y + self.widget.winfo_rooty() self.tipwindow = tw = Tk.Toplevel(self.widget) tw.wm_overrideredirect(1) tw.wm_geometry("+%d+%d" % (x, y)) try: # For Mac OS tw.tk.call("::tk::unsupported::MacWindowStyle", "style", tw._w, "help", "noActivates") except Tk.TclError: pass label = Tk.Label(tw, text=self.text, justify=Tk.LEFT, background="#ffffe0", relief=Tk.SOLID, borderwidth=1, ) label.pack(ipadx=1)
Example #20
Source File: Tkinter.py From BinderFilter with MIT License | 6 votes |
def _test(): root = Tk() text = "This is Tcl/Tk version %s" % TclVersion if TclVersion >= 8.1: try: text = text + unicode("\nThis should be a cedilla: \347", "iso-8859-1") except NameError: pass # no unicode support label = Label(root, text=text) label.pack() test = Button(root, text="Click me!", command=lambda root=root: root.test.configure( text="[%s]" % root.test['text'])) test.pack() root.test = test quit = Button(root, text="QUIT", command=root.destroy) quit.pack() # The following three commands are needed so the window pops # up on top on Windows... root.iconify() root.update() root.deiconify() root.mainloop()
Example #21
Source File: backend_tkagg.py From matplotlib-4-abaqus with MIT License | 6 votes |
def _init_toolbar(self): xmin, xmax = self.canvas.figure.bbox.intervalx height, width = 50, xmax-xmin Tk.Frame.__init__(self, master=self.window, width=int(width), height=int(height), borderwidth=2) self.update() # Make axes menu for text, tooltip_text, image_file, callback in self.toolitems: if text is None: # spacer, unhandled in Tk pass else: button = self._Button(text=text, file=image_file, command=getattr(self, callback)) if tooltip_text is not None: ToolTip.createToolTip(button, tooltip_text) self.message = Tk.StringVar(master=self) self._message_label = Tk.Label(master=self, textvariable=self.message) self._message_label.pack(side=Tk.RIGHT) self.pack(side=Tk.BOTTOM, fill=Tk.X)
Example #22
Source File: backend_tkagg.py From Computable with MIT License | 6 votes |
def _init_toolbar(self): xmin, xmax = self.canvas.figure.bbox.intervalx height, width = 50, xmax-xmin Tk.Frame.__init__(self, master=self.window, width=int(width), height=int(height), borderwidth=2) self.update() # Make axes menu for text, tooltip_text, image_file, callback in self.toolitems: if text is None: # spacer, unhandled in Tk pass else: button = self._Button(text=text, file=image_file, command=getattr(self, callback)) if tooltip_text is not None: ToolTip.createToolTip(button, tooltip_text) self.message = Tk.StringVar(master=self) self._message_label = Tk.Label(master=self, textvariable=self.message) self._message_label.pack(side=Tk.RIGHT) self.pack(side=Tk.BOTTOM, fill=Tk.X)
Example #23
Source File: backend_tkagg.py From Computable with MIT License | 6 votes |
def showtip(self, text): "Display text in tooltip window" self.text = text if self.tipwindow or not self.text: return x, y, _, _ = self.widget.bbox("insert") x = x + self.widget.winfo_rootx() + 27 y = y + self.widget.winfo_rooty() self.tipwindow = tw = Tk.Toplevel(self.widget) tw.wm_overrideredirect(1) tw.wm_geometry("+%d+%d" % (x, y)) try: # For Mac OS tw.tk.call("::tk::unsupported::MacWindowStyle", "style", tw._w, "help", "noActivates") except Tk.TclError: pass label = Tk.Label(tw, text=self.text, justify=Tk.LEFT, background="#ffffe0", relief=Tk.SOLID, borderwidth=1, ) label.pack(ipadx=1)
Example #24
Source File: Tkinter.py From oss-ftp with MIT License | 6 votes |
def _test(): root = Tk() text = "This is Tcl/Tk version %s" % TclVersion if TclVersion >= 8.1: try: text = text + unicode("\nThis should be a cedilla: \347", "iso-8859-1") except NameError: pass # no unicode support label = Label(root, text=text) label.pack() test = Button(root, text="Click me!", command=lambda root=root: root.test.configure( text="[%s]" % root.test['text'])) test.pack() root.test = test quit = Button(root, text="QUIT", command=root.destroy) quit.pack() # The following three commands are needed so the window pops # up on top on Windows... root.iconify() root.update() root.deiconify() root.mainloop()
Example #25
Source File: steam-idle.py From idle_master_py with GNU General Public License v2.0 | 6 votes |
def init_gui(str_app_id): gui = tk.Tk() gui.title('App ' + str_app_id) gui.resizable(0,0) try: url = "http://cdn.akamai.steamstatic.com/steam/apps/" + str_app_id + "/header_292x136.jpg" image_bytes = urlopen(url).read() data_stream = io.BytesIO(image_bytes) pil_image = Image.open(data_stream) tk_image = ImageTk.PhotoImage(pil_image) label = tk.Label(gui, image=tk_image) label.image = tk_image except: label = tk.Label(gui, text="Couldn't load image") label.pack() return gui
Example #26
Source File: listy.py From GeoVis with MIT License | 5 votes |
def Show(self): import numpy, PIL, PIL.Image, PIL.ImageTk, PIL.ImageDraw import Tkinter as tk import colour win = tk.Tk() nparr = numpy.array(self.grid.lists) npmin = numpy.min(nparr) npmax = numpy.max(nparr) minmaxdiff = npmax-npmin colorstops = [colour.Color("red").rgb,colour.Color("yellow").rgb,colour.Color("green").rgb] colorstops = [list(each) for each in colorstops] colorgrad = Listy(*colorstops) colorgrad.Convert("250*value") colorgrad.Resize(int(minmaxdiff)) valuerange = range(int(npmin),int(npmax)) colordict = dict(zip(valuerange,colorgrad.lists)) print len(valuerange),len(colorgrad.lists),len(colordict) print "minmax",npmin,npmax for ypos,horizline in enumerate(self.grid.lists): for xpos,value in enumerate(horizline): relval = value/float(npmax) self.grid.lists[ypos][xpos] = colorgrad.lists[int((len(colorgrad.lists)-1)*relval)] nparr = numpy.array(self.grid.lists,"uint8") print "np shape",nparr.shape img = PIL.Image.fromarray(nparr) drawer = PIL.ImageDraw.ImageDraw(img) size = 3 for knowncell in self.knowncells: x,y = (knowncell.x,knowncell.y) drawer.ellipse((x-size,y-size,x+size,y+size),fill="black") img.save("C:/Users/BIGKIMO/Desktop/test.png") tkimg = PIL.ImageTk.PhotoImage(img) lbl = tk.Label(win, image=tkimg) lbl.pack() win.mainloop() #INTERNAL USE ONLY
Example #27
Source File: viewer.py From mxnet-lambda with Apache License 2.0 | 5 votes |
def __init__(self, master, im): if im.mode == "1": # bitmap image self.image = ImageTk.BitmapImage(im, foreground="white") tkinter.Label.__init__(self, master, image=self.image, bd=0, bg="black") else: # photo image self.image = ImageTk.PhotoImage(im) tkinter.Label.__init__(self, master, image=self.image, bd=0) # # script interface
Example #28
Source File: CallTipWindow.py From oss-ftp with MIT License | 5 votes |
def showtip(self, text, parenleft, parenright): """Show the calltip, bind events which will close it and reposition it. """ # Only called in CallTips, where lines are truncated self.text = text if self.tipwindow or not self.text: return self.widget.mark_set(MARK_RIGHT, parenright) self.parenline, self.parencol = map( int, self.widget.index(parenleft).split(".")) self.tipwindow = tw = Toplevel(self.widget) self.position_window() # remove border on calltip window tw.wm_overrideredirect(1) try: # This command is only needed and available on Tk >= 8.4.0 for OSX # Without it, call tips intrude on the typing process by grabbing # the focus. tw.tk.call("::tk::unsupported::MacWindowStyle", "style", tw._w, "help", "noActivates") except TclError: pass self.label = Label(tw, text=self.text, justify=LEFT, background="#ffffe0", relief=SOLID, borderwidth=1, font = self.widget['font']) self.label.pack() self.checkhideid = self.widget.bind(CHECKHIDE_VIRTUAL_EVENT_NAME, self.checkhide_event) for seq in CHECKHIDE_SEQUENCES: self.widget.event_add(CHECKHIDE_VIRTUAL_EVENT_NAME, seq) self.widget.after(CHECKHIDE_TIME, self.checkhide_event) self.hideid = self.widget.bind(HIDE_VIRTUAL_EVENT_NAME, self.hide_event) for seq in HIDE_SEQUENCES: self.widget.event_add(HIDE_VIRTUAL_EVENT_NAME, seq)
Example #29
Source File: Tkdnd.py From oss-ftp with MIT License | 5 votes |
def attach(self, canvas, x=10, y=10): if canvas is self.canvas: self.canvas.coords(self.id, x, y) return if self.canvas: self.detach() if not canvas: return label = Tkinter.Label(canvas, text=self.name, borderwidth=2, relief="raised") id = canvas.create_window(x, y, window=label, anchor="nw") self.canvas = canvas self.label = label self.id = id label.bind("<ButtonPress>", self.press)
Example #30
Source File: recipe-52275.py From code with MIT License | 5 votes |
def plot(self, width_in=400, height_in=400): import colormap import Tkinter cmax = max(self.values()) cmin = min(self.values()) offset = 0.05*min(width_in, height_in) xmin, ymin, xmax, ymax = 0,0,self.size()[0], self.size()[1] scale = min(0.9*width_in, 0.9*height_in)/max(xmax-xmin, ymax-ymin) root = Tkinter.Tk() frame = Tkinter.Frame(root) frame.pack() text = Tkinter.Label(width=20, height=10, text='matrix sparsity') text.pack() canvas = Tkinter.Canvas(bg="black", width=width_in, height=height_in) canvas.pack() button = Tkinter.Button(frame, text="OK?", fg="red", command=frame.quit) button.pack() for index in self.keys(): ix, iy = index[0], ymax-index[1]-1 ya, xa = offset+scale*(ix ), height_in -offset-scale*(iy ) yb, xb = offset+scale*(ix+1), height_in -offset-scale*(iy ) yc, xc = offset+scale*(ix+1), height_in -offset-scale*(iy+1) yd, xd = offset+scale*(ix ), height_in -offset-scale*(iy+1) color = colormap.strRgb(self[index], cmin, cmax) canvas.create_polygon(xa, ya, xb, yb, xc, yc, xd, yd, fill=color) root.mainloop()