Python tkinter.Tk() Examples

The following are 30 code examples of tkinter.Tk(). 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: graphic.py    From ibllib with MIT License 9 votes vote down vote up
def strinput(title, prompt, default='COM', nullable=False):
    """
    Example:
    >>> strinput("RIG CONFIG", "Insert RE com port:", default="COM")
    """
    import tkinter as tk
    from tkinter import simpledialog
    root = tk.Tk()
    root.withdraw()
    ans = simpledialog.askstring(title, prompt, initialvalue=default)
    if (ans is None or ans == '' or ans == default) and not nullable:
        return strinput(title, prompt, default=default, nullable=nullable)
    else:
        return ans 
Example #2
Source File: overlay_label.py    From ultra_secret_scripts with GNU General Public License v3.0 7 votes vote down vote up
def __init__(self, text="IPSUM DOLOREM", pos="BR"):
        self.text = text
        self.pos = pos
        self.fg = "black"
        self.bg = "#f1f2f2"  # default transparent color
        self.width = 0
        self.height = 0

        tk = tkinter.Tk()
        self.label = tkinter.Label(tk, anchor="w")
        self.label.config(font=("Consolas", 8))
        self.label.master.overrideredirect(True)
        self.label.master.lift()
        self.label.master.wm_attributes("-topmost", True)
        self.label.master.wm_attributes("-disabled", True)
        self.label.master.wm_attributes("-transparentcolor", "#f1f2f3")

        hWindow = pywintypes.HANDLE(int(self.label.master.frame(), 16))
        exStyle = win32con.WS_EX_COMPOSITED | win32con.WS_EX_LAYERED | win32con.WS_EX_NOACTIVATE | \
                  win32con.WS_EX_TOPMOST | win32con.WS_EX_TRANSPARENT
        win32api.SetWindowLong(hWindow, win32con.GWL_EXSTYLE, exStyle)

        self.label.pack()
        self.update() 
Example #3
Source File: friendslist.py    From Tkinter-GUI-Programming-by-Example with MIT License 7 votes vote down vote up
def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.title('Tk Chat')
        self.geometry('700x500')

        self.menu = tk.Menu(self, bg="lightgrey", fg="black", tearoff=0)

        self.friends_menu = tk.Menu(self.menu, fg="black", bg="lightgrey", tearoff=0)
        self.friends_menu.add_command(label="Add Friend", command=self.show_add_friend_window)

        self.avatar_menu = tk.Menu(self.menu, fg="black", bg="lightgrey", tearoff=0)
        self.avatar_menu.add_command(label="Change Avatar", command=self.change_avatar)

        self.menu.add_cascade(label="Friends", menu=self.friends_menu)
        self.menu.add_cascade(label="Avatar", menu=self.avatar_menu)

        self.requester = Requester()

        self.show_login_screen() 
Example #4
Source File: texteditor.py    From Tkinter-GUI-Programming-by-Example with MIT License 6 votes vote down vote up
def generate_sub_menus(self, sub_menu_items):
        window_methods = [method_name for method_name in dir(self)
                          if callable(getattr(self, method_name))]
        tkinter_methods = [method_name for method_name in dir(tk.Tk)
                           if callable(getattr(tk.Tk, method_name))]

        my_methods = [method for method in set(window_methods) - set(tkinter_methods)]
        my_methods = sorted(my_methods)

        for item in sub_menu_items:
            sub_menu = tk.Menu(self.menu, tearoff=0, bg=self.background, fg=self.foreground)
            matching_methods = []
            for method in my_methods:
                if method.startswith(item):
                    matching_methods.append(method)

            for match in matching_methods:
                actual_method = getattr(self, match)
                method_shortcut = actual_method.__doc__.strip()
                friendly_name = ' '.join(match.split('_')[1:])
                sub_menu.add_command(label=friendly_name.title(), command=actual_method, accelerator=method_shortcut)

            self.menu.add_cascade(label=item.title(), menu=sub_menu)
            self.all_menus.append(sub_menu) 
Example #5
Source File: workflowcreator.py    From CEASIOMpy with Apache License 2.0 6 votes vote down vote up
def create_wf_gui():
    """ Create a GUI with Tkinter to fill the workflow to run

    Args:
        cpacs_path (str): Path to the CPACS file
        cpacs_out_path (str): Path to the output CPACS file
        module_list (list): List of module to inclue in the GUI

    """

    root = tk.Tk()
    root.title('Workflow Creator')
    root.geometry('475x490+400+100')
    my_gui = WorkFlowGUI()
    my_gui.mainloop()
    disg = my_gui.Options

    root.iconify() # Not super solution but only way to make it close on Mac
    root.destroy()

    return disg 
Example #6
Source File: texteditor.py    From Tkinter-GUI-Programming-by-Example with MIT License 6 votes vote down vote up
def generate_sub_menus(self, sub_menu_items):
        window_methods = [method_name for method_name in dir(self)
                          if callable(getattr(self, method_name))]
        tkinter_methods = [method_name for method_name in dir(tk.Tk)
                           if callable(getattr(tk.Tk, method_name))]

        my_methods = [method for method in set(window_methods) - set(tkinter_methods)]
        my_methods = sorted(my_methods)

        for item in sub_menu_items:
            sub_menu = tk.Menu(self.menu, tearoff=0, bg=self.background, fg=self.foreground)
            matching_methods = []
            for method in my_methods:
                if method.startswith(item):
                    matching_methods.append(method)

            for match in matching_methods:
                actual_method = getattr(self, match)
                method_shortcut = actual_method.__doc__.strip()
                friendly_name = ' '.join(match.split('_')[1:])
                sub_menu.add_command(label=friendly_name.title(), command=actual_method, accelerator=method_shortcut)

            self.menu.add_cascade(label=item.title(), menu=sub_menu)
            self.all_menus.append(sub_menu) 
Example #7
Source File: window.py    From LPHK with GNU General Public License v3.0 6 votes vote down vote up
def make():
    global root
    global app
    global root_destroyed
    global redetect_before_start
    root = tk.Tk()
    root_destroyed = False
    root.protocol("WM_DELETE_WINDOW", close)
    root.resizable(False, False)
    if MAIN_ICON != None:
        if os.path.splitext(MAIN_ICON)[1].lower() == ".gif":
            root.call('wm', 'iconphoto', root._w, tk.PhotoImage(file=MAIN_ICON))
        else:
            root.iconbitmap(MAIN_ICON)
    app = Main_Window(root)
    app.raise_above_all()
    app.after(100, app.connect_lp)
    app.mainloop() 
Example #8
Source File: friendslist.py    From Tkinter-GUI-Programming-by-Example with MIT License 6 votes vote down vote up
def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.title('Tk Chat')
        self.geometry('700x500')

        self.menu = tk.Menu(self, bg="lightgrey", fg="black", tearoff=0)

        self.friends_menu = tk.Menu(self.menu, fg="black", bg="lightgrey", tearoff=0)
        self.friends_menu.add_command(label="Add Friend", command=self.add_friend)

        self.menu.add_cascade(label="Friends", menu=self.friends_menu)

        self.configure(menu=self.menu)

        self.canvas = tk.Canvas(self, bg="white")
        self.canvas_frame = tk.Frame(self.canvas)

        self.scrollbar = ttk.Scrollbar(self, orient="vertical", command=self.canvas.yview)
        self.canvas.configure(yscrollcommand=self.scrollbar.set)

        self.scrollbar.pack(side=tk.LEFT, fill=tk.Y)
        self.canvas.pack(side=tk.LEFT, expand=1, fill=tk.BOTH)

        self.friends_area = self.canvas.create_window((0, 0), window=self.canvas_frame, anchor="nw")

        self.bind_events()

        self.load_friends() 
Example #9
Source File: wicc_view_splash.py    From WiCC with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self):
        root = tk.Tk()
        # show no frame
        root.overrideredirect(True)

        # get screen width and height
        ws = root.winfo_screenwidth()
        hs = root.winfo_screenheight()
        # calculate position x, y
        x = (ws / 2) - (self.width / 2)
        y = (hs / 2) - (self.height / 2)
        root.geometry('%dx%d+%d+%d' % (self.width, self.height, x, y))

        image = tk.PhotoImage(file=self.image_file)
        canvas = tk.Canvas(root, height=self.height, width=self.width, bg="brown")
        canvas.create_image(self.width/2, self.height/2, image=image)
        canvas.pack()

        root.after(2500, root.destroy)
        root.mainloop() 
Example #10
Source File: program13.py    From python-gui-demos with MIT License 6 votes vote down vote up
def launchApp():
    root = tk.Tk()
    App(root)
    tk.mainloop() 
Example #11
Source File: dashboard.py    From crappy with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, labels, nb_digits, queue):
      self.root = Tk()
      self.root.title('Dashboard')
      self.root.resizable(width=False, height=False)
      self.first_column = labels
      self.nb_digits = nb_digits
      self.c2 = []
      self.queue = queue
      # Creating the first and second column. Second column will be updated.
      for row_index, first_column in enumerate(self.first_column):
        Label(self.root, text=first_column, borderwidth=15,
              font=("Courier bold", 48)).grid(row=row_index, column=0)
        self.c2.append(
          Label(self.root, text='', borderwidth=15, font=("Courier bold", 48)))
        self.c2[row_index].grid(row=row_index, column=1)
      self.i = 0
      while True:
        self.update() 
Example #12
Source File: nemo_app.py    From razzy-spinner with GNU General Public License v3.0 6 votes vote down vote up
def app():
    global root, sz, rz, rex0
    root = tk.Tk()
    root.resizable(height=False,width=True)
    root.title(windowTitle)
    root.minsize(width=250,height=0)
    sz = FindZone("find",initialFind,initialText)
    sz.fld.bind("<Button-1>",launchRefresh)
    sz.fld.bind("<ButtonRelease-1>",launchRefresh)
    sz.fld.bind("<B1-Motion>",launchRefresh)
    sz.rexSel = re.compile("")
    rz = ReplaceZone("repl",initialRepl,"")
    rex0 = re.compile(r"(?<!\\)\\([0-9]+)")
    root.bind_all("<Key>",launchRefresh)
    launchRefresh(None)
    root.mainloop() 
Example #13
Source File: __init__.py    From 3DGCN with MIT License 6 votes vote down vote up
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 #14
Source File: tk.py    From Jtyoui with MIT License 6 votes vote down vote up
def ui():
    root = tkinter.Tk()
    root.title('PDF和照片互转器')  # 标题
    root.resizable(width=False, height=False)  # 防止大小调整
    canvas = tkinter.Canvas(root, width=450, height=320, highlightthickness=0)  # 创建画布
    photo = tkinter.PhotoImage(file=file_zip_path + os.sep + 'pdf.png')  # 获取背景图片的网络连接
    canvas.create_image(225, 160, image=photo)

    select_dir_button = tkinter.Button(root, text="选择照片文件夹", command=select_dir, bg='yellow')  # 创建按钮
    select_pdf_button = tkinter.Button(root, text="选择PDF文件", command=select_pdf, bg='green')
    click_button = tkinter.Button(root, text="点击执行", command=start, bg='blue')

    select_dir_button.pack()  # 启动按钮
    select_pdf_button.pack()
    click_button.pack()

    canvas.create_window(240, 120, width=100, height=30, window=select_dir_button)  # 将按钮创建到画布
    canvas.create_window(240, 190, width=100, height=30, window=select_pdf_button)
    canvas.create_window(240, 260, width=100, height=30, window=click_button)
    canvas.pack()  # 启动画布
    root.mainloop()  # 主程序循环 
Example #15
Source File: earlyinit.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
def check_pyqt():
    """Check if PyQt core modules (QtCore/QtWidgets) are installed."""
    for name in ['PyQt5.QtCore', 'PyQt5.QtWidgets']:
        try:
            importlib.import_module(name)
        except ImportError as e:
            text = _missing_str(name)
            text = text.replace('<b>', '')
            text = text.replace('</b>', '')
            text = text.replace('<br />', '\n')
            text = text.replace('%ERROR%', str(e))
            if tkinter and '--no-err-windows' not in sys.argv:
                root = tkinter.Tk()
                root.withdraw()
                tkinter.messagebox.showerror("qutebrowser: Fatal error!", text)
            else:
                print(text, file=sys.stderr)
            if '--debug' in sys.argv or '--no-err-windows' in sys.argv:
                print(file=sys.stderr)
                traceback.print_exc()
            sys.exit(1) 
Example #16
Source File: earlyinit.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
def early_init(args):
    """Do all needed early initialization.

    Note that it's vital the other earlyinit functions get called in the right
    order!

    Args:
        args: The argparse namespace.
    """
    # First we initialize the faulthandler as early as possible, so we
    # theoretically could catch segfaults occurring later during earlyinit.
    init_faulthandler()
    # Here we check if QtCore is available, and if not, print a message to the
    # console or via Tk.
    check_pyqt()
    # Init logging as early as possible
    init_log(args)
    # Now we can be sure QtCore is available, so we can print dialogs on
    # errors, so people only using the GUI notice them as well.
    check_libraries()
    check_qt_version()
    configure_pyqt()
    check_ssl_support()
    check_optimize_flag() 
Example #17
Source File: cameraConfig.py    From crappy with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self,camera):
    self.camera = camera
    self.label_shape = 800,600
    self.scale_length = 350
    self.last_reticle_pos = (0,0)
    self.root = tk.Tk()
    self.root.protocol("WM_DELETE_WINDOW",self.stop)
    self.zoom_step = .1
    self.reset_zoom()
    self.img = self.camera.read_image()[1]
    self.on_resize()
    self.convert_img()
    self.create_window()
    self.update_img()
    self.start_histogram()
    self.update_histogram()
    self.refresh_rate = 1/50
    self.low = 0
    self.high = 255
    self.t = time()
    self.t_fps = self.t
    self.go = True
    #self.main() 
Example #18
Source File: client_graphics.py    From Pyro5 with MIT License 6 votes vote down vote up
def __init__(self):
        self.root = tkinter.Tk()
        self.root.title("Mandelbrot (Pyro multi CPU core version)")
        canvas = tkinter.Canvas(self.root, width=res_x, height=res_y, bg="#000000")
        canvas.pack()
        self.img = tkinter.PhotoImage(width=res_x, height=res_y)
        canvas.create_image((res_x/2, res_y/2), image=self.img, state="normal")
        with locate_ns() as ns:
            mandels = ns.yplookup(meta_any={"class:mandelbrot_calc_color"})
            mandels = list(mandels.items())
        print("{0} mandelbrot calculation servers found.".format(len(mandels)))
        if not mandels:
            raise ValueError("launch at least one mandelbrot calculation server before starting this")
        self.mandels = [uri for _, (uri, meta) in mandels]
        self.pool = futures.ThreadPoolExecutor(max_workers=len(self.mandels))
        self.tasks = []
        self.start_time = time.time()
        for line in range(res_y):
            self.tasks.append(self.calc_new_line(line))
        self.root.after(100, self.draw_results)
        tkinter.mainloop() 
Example #19
Source File: env.py    From Reinforcement_Learning_for_Traffic_Light_Control with Apache License 2.0 5 votes vote down vote up
def visual_init(self):
        window = tk.Tk()
        window.title('my window')
        window.geometry('500x500')
        self.canvas = tk.Canvas(window, bg='white', height=200, width=300)
        self.canvas_ = tk.Canvas(window, bg='white', height=200, width=300) 
Example #20
Source File: example.py    From Traffic-Signs-and-Object-Detection with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):

        tk.Tk.__init__(self)

        self.geometry('%dx%d+500+500' % (WIDTH,HEIGHT))
        self.title('GooMPy')

        self.canvas = tk.Canvas(self, width=WIDTH, height=HEIGHT)

        self.canvas.pack()

        self.bind("<Key>", self.check_quit)
        self.bind('<B1-Motion>', self.drag)
        self.bind('<Button-1>', self.click)

        self.label = tk.Label(self.canvas)

        self.radiogroup = tk.Frame(self.canvas)
        self.radiovar = tk.IntVar()
        self.maptypes = ['roadmap', 'terrain', 'satellite', 'hybrid']
        self.add_radio_button('Road Map',  0)
        self.add_radio_button('Terrain',   1)
        self.add_radio_button('Satellite', 2)
        self.add_radio_button('Hybrid',    3)

        self.zoom_in_button  = self.add_zoom_button('+', +1)
        self.zoom_out_button = self.add_zoom_button('-', -1)

        self.zoomlevel = ZOOM

        maptype_index = 0
        self.radiovar.set(maptype_index)

        self.goompy = GooMPy(WIDTH, HEIGHT, LATITUDE, LONGITUDE, ZOOM, MAPTYPE)

        self.restart() 
Example #21
Source File: main.py    From Bitcoin-Trading-Client with GNU General Public License v2.0 5 votes vote down vote up
def addBottomIndicator(what):
    global bottomIndicator
    global DatCounter

    if DataPace == "tick":
        popupmsg("Indicators in Tick Data not available, choose 1 minute tf if you want short term.")

    if what == "none":
        bottomIndicator = what
        DatCounter = 9000

    elif what == "rsi":
        rsiQ = tk.Tk()
        rsiQ.wm_title("Periods?")
        label = ttk.Label(rsiQ, text="Choose how many periods you want each RSI calculation to consider.\nThese periods are contingent on your current time settings on the chart. 1 period = 1 OHLC candlestick.", font=NORM_FONT)
        label.pack(side="top", fill="x", pady=10)

        e = ttk.Entry(rsiQ)
        e.insert(0,14)
        e.pack()
        e.focus_set()

        def callback():
            periods = (e.get())
            group = []
            group.append("rsi")
            group.append(periods)
            bottomIndicator = group
            DatCounter = 9000
            print("set top indicator to",group)
            rsiQ.destroy()
        
        b = ttk.Button(rsiQ, text="Submit", width=10, command=callback)
        b.pack()

        tk.mainloop()

    elif what == "macd":
        bottomIndicator = "macd"
        DatCounter = 9000 
Example #22
Source File: graphic.py    From ibllib with MIT License 5 votes vote down vote up
def numinput(title, prompt, default=None, minval=None, maxval=None,
             nullable=False, askint=False):
    root = tk.Tk()
    root.withdraw()
    ask = simpledialog.askinteger if askint else simpledialog.askfloat
    ans = ask(
        title, prompt, initialvalue=default, minvalue=minval, maxvalue=maxval)
    if ans == 0:
        return ans
    elif not ans and not nullable:
        return numinput(
            title, prompt, default=default, minval=minval, maxval=maxval,
            nullable=nullable, askint=askint)
    return ans 
Example #23
Source File: graphic.py    From ibllib with MIT License 5 votes vote down vote up
def popup(title, msg):
    root = tk.Tk()
    root.withdraw()
    messagebox.showinfo(title, msg)
    root.quit() 
Example #24
Source File: normal_graphics.py    From Pyro5 with MIT License 5 votes vote down vote up
def __init__(self):
        self.root = tkinter.Tk()
        self.root.title("Mandelbrot (Single CPU core)")
        canvas = tkinter.Canvas(self.root, width=res_x, height=res_y, bg="#000000")
        canvas.pack()
        self.img = tkinter.PhotoImage(width=res_x, height=res_y)
        canvas.create_image((res_x/2, res_y/2), image=self.img, state="normal")
        self.mandel = MandelbrotColorPixels()
        self.start_time = time.time()
        self.root.after(1000, lambda: self.draw_line(0))
        tkinter.mainloop() 
Example #25
Source File: gui.py    From SEM with MIT License 5 votes vote down vote up
def main(args):
    root = tkinter.Tk()
    root.title("SEM")
    root.minsize(width=380, height=200)
    
    SemTkMainWindow(root, args.resources, log_level=args.log_level).pack()
    
    root.mainloop() 
Example #26
Source File: opencv_windows_management.py    From OpenCV-Python-Tutorial with MIT License 5 votes vote down vote up
def __init__(self):
        self.windows = dict()

        root = tk.Tk()
        screen_width = root.winfo_screenwidth()
        screen_height = root.winfo_screenheight()
        self.screen_size = (screen_width, screen_height)  # (1280, 800)
        root.quit() 
Example #27
Source File: photoboothapp.py    From OpenCV-Python-Tutorial with MIT License 5 votes vote down vote up
def __init__(self, vs, outputPath):
        # store the video stream object and output path, then initialize
        # the most recently read frame, thread for reading frames, and
        # the thread stop event
        self.vs = vs
        self.outputPath = outputPath
        self.frame = None
        self.thread = None
        self.stopEvent = None

        # initialize the root window and image panel
        self.root = tki.Tk()
        self.panel = None

        # create a button, that when pressed, will take the current
        # frame and save it to file
        btn = tki.Button(self.root, text="Snapshot!",
                         command=self.takeSnapshot)
        btn.pack(side="bottom", fill="both", expand="yes", padx=10,
                 pady=10)

        # start a thread that constantly pools the video sensor for
        # the most recently read frame
        self.stopEvent = threading.Event()
        self.thread = threading.Thread(target=self.videoLoop, args=())
        self.thread.start()

        # set a callback to handle when the window is closed
        self.root.wm_title("PyImageSearch PhotoBooth")
        self.root.wm_protocol("WM_DELETE_WINDOW", self.onClose) 
Example #28
Source File: cross.py    From Reinforcement_Learning_for_Traffic_Light_Control with Apache License 2.0 5 votes vote down vote up
def visual_init(self):
        window = tk.Tk()
        window.title('my window')
        window.geometry('500x500')
        self.canvas = tk.Canvas(window, bg='white', height=200, width=300)
        self.canvas_ = tk.Canvas(window, bg='white', height=200, width=300) 
Example #29
Source File: blynclight.py    From blynclight with MIT License 5 votes vote down vote up
def __init__(self):
		"""Constructor"""
		self._queue = queue.Queue()
		self._root = tkinter.Tk()
		self._root.title('Blynclight Simulator')
		self._root.geometry('250x250')
		self._root.bind('<<UpdateColor>>', self._update_color)
		self._root.bind('<<Quit>>', self._quit)
		self.is_ready = threading.Event() 
Example #30
Source File: annotation_gui.py    From SEM with MIT License 5 votes vote down vote up
def main(args):
    root = tkinter.Tk()
    root.title("SEM")
    AnnotationTool(root, args.log_level, documents=args.documents, tagset=args.tagset).pack(expand=1, fill="both")
    root.mainloop()