예제 #1
0
# RADIO BUTTON
def radio_changed():
    #Change cursor, disable the relaunch uf the video_stream, load model and return everything to running mode
    #app.config(cursor="wait")
    PAUSE_FEED = True
    if MODE is not "DEBUG":
        model = load_model("models/" + files[selected_int.get()])
    PAUSE_FEED = False
    window.title(WINDOW_TITLE + " - " + files[selected_int.get()] +
                 WINDOW_TITLE_CONFIG)
    window.config(cursor="")
    video_stream()


menu = tk.Menu(window)
model_menu = tk.Menu(menu)

selected_int = tk.IntVar()
for i, model in enumerate(files):
    model_menu.add_radiobutton(label=model,
                               variable=selected_int,
                               value=i,
                               command=radio_changed)

menu.add_cascade(label="Model", menu=model_menu)
window.config(menu=menu)

# CAMERA FEED
label_camera = tk.Label(app)
label_camera.grid(column=0, row=0)
예제 #2
0
def create_TK_Canvas():
    root = tk.Tk()
    root.title(TITLE)
    global TK_Canvas, CONSOLEVAR, VI_MENU, VI_AGENT_MENU, QLEARN_MENU, R, SEGMENTS  #, SEGMENTS_FOR_POLICY
    global NOISE_VAR, NGOALS_VAR, R_VAR, G_VAR, DISPLAY_VALS_VAR, Q_VAR, ALPHA_VAR, EPSILON_VAR, EXPL_VAR
    global VI_POLICY_VAR, QL_POLICY_VAR
    TK_Canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT)
    TK_Canvas.configure(background="#ccccff")  # Blue-gray
    TK_Canvas.pack(fill="both", expand=True)
    TK_Canvas.create_rectangle(
        0, HEIGHT * 0.3 - 70, WIDTH, HEIGHT,
        fill="#888888")  # Background to make q values more visible.

    menubar = tk.Menu(root)

    # create a pulldown menu, and add it to the menu bar
    filemenu = tk.Menu(menubar, tearoff=0)
    filemenu.add_command(label="Restart with 2 disks",
                         command=lambda: MDP_command("NDISKS", 2))
    filemenu.add_command(label="Restart with 3 disks",
                         command=lambda: MDP_command("NDISKS", 3))
    filemenu.add_command(label="Restart with 4 disks",
                         command=lambda: MDP_command("NDISKS", 4))
    filemenu.add_command(label="Exit", command=exit)
    menubar.add_cascade(label="File", menu=filemenu)

    # create more pulldown menus
    NOISE_VAR = tk.IntVar()
    MDP_Noise_menu = tk.Menu(menubar, tearoff=0)
    MDP_Noise_menu.add_checkbutton(label="0% (deterministic)", var=NOISE_VAR, onvalue=1, offvalue=2,\
                        command=lambda :MDP_command("noise",0))
    MDP_Noise_menu.add_checkbutton(label="20%", var=NOISE_VAR, onvalue=2, offvalue=1,\
                        command=lambda :MDP_command("noise",0.2))
    menubar.add_cascade(label="MDP Noise", menu=MDP_Noise_menu)

    MDP_Rewards_menu = tk.Menu(menubar, tearoff=0)
    NGOALS_VAR = tk.IntVar()
    MDP_Rewards_menu.add_checkbutton(label="One goal, R=100", var=NGOALS_VAR, onvalue=1, offvalue=2,\
                        command=lambda :MDP_command("ngoals",1))
    MDP_Rewards_menu.add_checkbutton(label="Two goals, R=100 and R=10", var=NGOALS_VAR, onvalue=2, offvalue=1,\
                        command=lambda :MDP_command("ngoals",2))

    R_VAR = tk.IntVar()
    MDP_Rewards_menu.add_checkbutton(label="Living R=0", var=R_VAR, onvalue=1,\
                        command=lambda :MDP_command("living_reward",0))
    MDP_Rewards_menu.add_checkbutton(label="Living R= -0.01", var=R_VAR, onvalue=2,\
                        command=lambda :MDP_command("living_reward",-0.01))
    MDP_Rewards_menu.add_checkbutton(label="Living R= -0.1", var=R_VAR, onvalue=3,\
                        command=lambda :MDP_command("living_reward",-0.1))
    MDP_Rewards_menu.add_checkbutton(label="Living R= +0.1", var=R_VAR, onvalue=4,\
                        command=lambda :MDP_command("living_reward",0.1))
    menubar.add_cascade(label="MDP Rewards", menu=MDP_Rewards_menu)

    G_VAR = tk.IntVar()
    gammamenu = tk.Menu(menubar, tearoff=0)
    gammamenu.add_checkbutton(label="\u03b3 = 1.0", var=G_VAR, onvalue=1,\
                        command=lambda :MDP_command("set_gamma",1.0))
    gammamenu.add_checkbutton(label="\u03b3 = 0.99", var=G_VAR, onvalue=2,\
                        command=lambda :MDP_command("set_gamma",0.99))
    gammamenu.add_checkbutton(label="\u03b3 = 0.9", var=G_VAR, onvalue=3,\
                        command=lambda :MDP_command("set_gamma",0.9))
    gammamenu.add_checkbutton(label="\u03b3 = 0.5", var=G_VAR, onvalue=4,\
                        command=lambda :MDP_command("set_gamma",0.5))
    menubar.add_cascade(label="Discount", menu=gammamenu)

    DISPLAY_VALS_VAR = tk.IntVar()
    VI_MENU = tk.Menu(menubar, tearoff=0)
    VI_MENU.add_checkbutton(label="Show state values (V) from VI", var=DISPLAY_VALS_VAR, onvalue=1,\
                        command=lambda :MDP_command("show_values", 1))
    VI_MENU.add_checkbutton(label="Show Q values from VI", var=DISPLAY_VALS_VAR, onvalue=2,\
                        command=lambda :MDP_command("show_values", 2))
    VI_MENU.add_command(label="Reset state values (V) and Q values for VI to 0",\
                        command=lambda :MDP_command("Value_Iteration",0))
    VI_MENU.add_command(label="1 step of VI",\
                        command=lambda :MDP_command("Value_Iteration",1))
    VI_MENU.add_command(label="10 steps of VI",\
                        command=lambda :MDP_command("Value_Iteration",10))
    VI_MENU.add_command(label="100 steps of VI",\
                        command=lambda :MDP_command("Value_Iteration",100))
    VI_POLICY_VAR = tk.BooleanVar()
    VI_MENU.add_checkbutton(label="Show Policy from VI", var=VI_POLICY_VAR, onvalue=True,\
                        command=lambda :MDP_command("Show_Policy_from_VI",True))
    menubar.add_cascade(label="Value Iteration", menu=VI_MENU)

    VI_AGENT_MENU = tk.Menu(menubar, tearoff=0)
    VI_AGENT_MENU.add_command(label="Reset state to s0",\
                        command=lambda :MDP_command("Agent",0))
    VI_AGENT_MENU.add_command(label="Perform 1 action",\
                        command=lambda :MDP_command("Agent",1))
    VI_AGENT_MENU.add_command(label="Perform 10 actions",\
                        command=lambda :MDP_command("Agent",10))
    VI_AGENT_MENU.add_command(label="Perform 100 actions",\
                        command=lambda :MDP_command("Agent",100))
    menubar.add_cascade(label="VI Agent", menu=VI_AGENT_MENU)

    QLEARN_MENU = tk.Menu(menubar, tearoff=0)
    Q_VAR = tk.BooleanVar()
    QLEARN_MENU.add_checkbutton(label="Show state values (V) from QL", var=DISPLAY_VALS_VAR, onvalue=3,\
                        command=lambda :MDP_command("show_values", 3))
    QLEARN_MENU.add_checkbutton(label="Show Q values from QL", var=DISPLAY_VALS_VAR, onvalue=4,\
                        command=lambda :MDP_command("show_values", 4))
    QLEARN_MENU.add_command(label="Reset state values (V) and Q values for QL to 0",\
                        command=lambda :MDP_command("QLearn",-2))
    QLEARN_MENU.add_command(label="Reset state to s0",\
                        command=lambda :MDP_command("QLearn",-1))
    CONSOLEVAR = tk.BooleanVar()
    QLEARN_MENU.add_checkbutton(label="User driving console", var=CONSOLEVAR, onvalue=True, offvalue=False,\
                        command=open_user_driving_console)
    QLEARN_MENU.add_command(label="Perform 1 action",\
                        command=lambda :MDP_command("QLearn",1))
    QLEARN_MENU.add_command(label="Perform 10 actions",\
                        command=lambda :MDP_command("QLearn",10))
    QLEARN_MENU.add_command(label="Perform 100 actions",\
                        command=lambda :MDP_command("QLearn",100))
    QLEARN_MENU.add_command(label="Train for 1000 transitions",\
                        command=lambda :MDP_command("QLearn",-1000))
    QL_POLICY_VAR = tk.BooleanVar()
    QLEARN_MENU.add_checkbutton(label="Show Policy from QL", var=QL_POLICY_VAR, onvalue=True,\
                        command=lambda :MDP_command("Show_Policy_from_QL",True))
    menubar.add_cascade(label="Q-Learning", menu=QLEARN_MENU)

    QL_PARAM_MENU = tk.Menu(menubar, tearoff=0)
    ALPHA_VAR = tk.IntVar()
    QL_PARAM_MENU.add_checkbutton(label="Fixed \u03b1=0.1", var=ALPHA_VAR, onvalue=1,\
                        command=lambda :MDP_command("alpha",1))
    QL_PARAM_MENU.add_checkbutton(label="Fixed \u03b1=0.2", var=ALPHA_VAR, onvalue=2,\
                        command=lambda :MDP_command("alpha",2))
    QL_PARAM_MENU.add_checkbutton(label="Custom \u03b1", var=ALPHA_VAR, onvalue=3,\
                        command=lambda :MDP_command("alpha",3))
    EPSILON_VAR = tk.IntVar()
    QL_PARAM_MENU.add_checkbutton(label="Fixed \u03b5=0.1", var=EPSILON_VAR, onvalue=1,\
                        command=lambda :MDP_command("epsilon",1))
    QL_PARAM_MENU.add_checkbutton(label="Fixed \u03b5=0.2", var=EPSILON_VAR, onvalue=2,\
                        command=lambda :MDP_command("epsilon",2))
    QL_PARAM_MENU.add_checkbutton(label="Custom \u03b5", var=EPSILON_VAR, onvalue=3,\
                        command=lambda :MDP_command("epsilon",3))
    EXPL_VAR = tk.BooleanVar()
    QL_PARAM_MENU.add_checkbutton(label="Use exploration function (and reset Q values)", var=EXPL_VAR, onvalue=True,\
                        command=lambda :MDP_command("Exploration",0))
    menubar.add_cascade(label="QL Params", menu=QL_PARAM_MENU)
    # Check if autograder is available:
    try:
        import basic_autograder as bag
        filemenu.add_command(label="Basic autograde",
                             command=bag.basic_autograde)
    except:
        pass
    try:
        import advanced_autograder as aag
        filemenu.add_command(label="Advanced autograde",
                             command=aag.advanced_autograde)
    except:
        pass
    # Check is a special script is available (to setup for testing, etc.)
    try:
        import script_for_TOH_MDP as script
        filemenu.add_command(label="Run script",
                             command=lambda: MDP_command("Run_script", True))
    except:
        pass

    # Finally, do some initialization needed for policy display and displaying the user driving console.
    Ra = R * 1.6
    SEGMENTS = [(int(R * x), int(R * y), int(Ra * x), int(Ra * y))
                for (x, y) in DRIVING_ARROW_XYS]

    # display the menu
    root.config(menu=menubar)
예제 #3
0
파일: ui_tk.py 프로젝트: qnga/pyglossary
		def valueCellClicked(event, optName):
			if not optName:
				return
			prop = optionsProp[optName]
			propValues = prop.values
			if not propValues:
				if prop.customValue:
					self.valueMenuItemCustomSelected(treev, format, optName, None)
				else:
					log.error(
						f"invalid option {optName}, values={propValues}"
						f", customValue={prop.customValue}"
					)
				return
			if prop.typ == "bool":
				rawValue = treev.set(optName, self.valueCol)
				if rawValue == "":
					value = False
				else:
					value, isValid = prop.evaluate(rawValue)
					if not isValid:
						log.error(f"invalid {optName} = {rawValue!r}")
						value = False
				treev.set(optName, self.valueCol, str(not value))
				treev.set(optName, "#1", "1")  # enable it
				return
			menu = tk.Menu(
				master=treev,
				title=optName,
				tearoff=False,
			)
			self.menu = menu  # to destroy it later
			if prop.customValue:
				menu.add_command(
					label="[Custom Value]",
					command=lambda: self.valueMenuItemCustomSelected(
						treev,
						format,
						optName,
						menu,
					),
				)
			groupedValues = None
			if len(propValues) > 10:
				groupedValues = prop.groupValues()
			maxItemW = 0
			if groupedValues:
				for groupName, subValues in groupedValues.items():
					if subValues is None:
						menu.add_command(
							label=str(value),
							command=lambda value=value: valueMenuItemSelected(optName, menu, value),
						)
						maxItemW = max(maxItemW, tkFont.Font().measure(str(value)))
					else:
						subMenu = tk.Menu(tearoff=False)
						for subValue in subValues:
							subMenu.add_command(
								label=str(subValue),
								command=lambda value=subValue: valueMenuItemSelected(
									optName,
									menu,
									value,
								),
							)
						menu.add_cascade(label=groupName, menu=subMenu)
						maxItemW = max(maxItemW, tkFont.Font().measure(groupName))
			else:
				for value in propValues:
					value = str(value)
					menu.add_command(
						label=value,
						command=lambda value=value: valueMenuItemSelected(optName, menu, value),
					)

			def close():
				menu.destroy()
				self.menu = None

			menu.add_command(
				label="[Close]",
				command=close,
			)
			try:
				menu.tk_popup(
					event.x_root,
					event.y_root,
				)
				# do not pass the third argument (entry), so that the menu
				# apears where the pointer is on its top-left corner
			finally:
				# make sure to release the grab (Tk 8.0a1 only)
				menu.grab_release()
예제 #4
0
파일: ibook.py 프로젝트: zhbi98/ibook
 def __init__(self, rclick_menu=tkinter.Menu(window)):
     self.rclick_menu = rclick_menu
예제 #5
0
    if show_visual:

        # Build the main GUI window
        root = tkinter.Tk()
        root.wm_title("Environment Model")  # Set window's title

        # Add canvas to the GUI window
        fig = matplotlib.pyplot.figure(figsize=(7, 7))
        ax = fig.add_axes([0, 0, 300, 300])

        canvas = matplotlib.backends.backend_tkagg.FigureCanvasTkAgg(
            fig, master=root)
        canvas._tkcanvas.pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)

        # Add menu
        menu = tkinter.Menu(root)
        root.config(menu=menu)
        model_menu = tkinter.Menu(menu)
        menu.add_cascade(label="Model", menu=model_menu)
        model_menu.add_command(label="Run model", command=run)

        # Wait for GUI events
        tkinter.mainloop()

    else:
        for i in range(num_of_iterations):
            single_iteration()

        # Output the sum the environment to `output/stored.txt`
        total_stored(agents)
예제 #6
0
    def initUI(self):

        self.master.title("Seed Annotator")
        self.pack(fill=BOTH, expand=True)

        self.columnconfigure(1, weight=1)
        self.columnconfigure(3, pad=7)
        self.rowconfigure(3, weight=1)
        self.rowconfigure(5, pad=7)

        # Create class drop down
        self.seed_classes = ['Add a new class...']

        self.current_class = tk.StringVar(self.master)
        self.current_class.set(self.seed_classes[0])
        self.classDropdown = tk.OptionMenu(self,
                                           self.current_class,
                                           *self.seed_classes,
                                           command=self.dropdown_callback)
        self.classDropdown.config(width=15)
        self.classDropdown.grid(row=2, column=3, pady=5, sticky=W)

        self.class_select_label = tk.Label(self,
                                           text="Select a class: ",
                                           font='Helvetica 7 bold')
        self.class_select_label.grid(row=1, column=3, pady=(15, 0), sticky=W)

        self.autoann_label = tk.Label(self,
                                      text="Auto-annotation options:",
                                      font='Helvetica 7 bold')
        self.autoann_label.grid(row=3, column=3, pady=10, sticky=tk.NW)

        self.gen_bbox_button = tk.Button(self,
                                         text="Generate bounding boxes",
                                         command=self.gen_dataset_bboxes)
        self.gen_bbox_button.grid(row=3, column=3, sticky=tk.NW, pady=90)

        self.filter_empty = tk.IntVar(self.master)
        self.filter_empty_check = tk.Checkbutton(self,
                                                 text="Discard empty samples",
                                                 variable=self.filter_empty)
        self.filter_empty_check.grid(row=3, column=3, sticky=tk.NW, pady=40)

        self.homogeneous = tk.IntVar(self.master)
        self.homogeneous_check = tk.Checkbutton(self,
                                                text="Homogeneous sample",
                                                variable=self.homogeneous)
        self.homogeneous_check.grid(row=3, column=3, sticky=tk.NW, pady=60)

        # Bind arrow key events
        self.bind('<Right>', self.next_sample)
        self.bind('<Left>', self.prev_sample)
        self.bind('s', self.save_annotation)
        self.bind('<Delete>', self.delete_sample)
        self.bind('<Up>', self.prev_class)
        self.bind('<Down>', self.next_class)

        # Create image canvas
        self.canvas = tk.Canvas(self,
                                width=300,
                                height=300,
                                background='white')
        self.canvas.grid(row=0,
                         column=0,
                         columnspan=2,
                         rowspan=4,
                         pady=10,
                         padx=10,
                         sticky=tk.NW)
        self.image_on_canvas = self.canvas.create_image(0, 0, image=None)

        # Create canvas mouse handlers for rectangles
        self.canvas.bind("<Button-1>", self.startRect)
        self.canvas.bind("<ButtonRelease-1>", self.stopRect)
        self.canvas.bind("<Motion>", self.movingRect)
        self.canvas.bind("<Button-3>", self.deleteRect)

        # Create canvas variables for bbox drawing
        self.rectx0 = 0
        self.recty0 = 0
        self.rectx1 = 0
        self.recty1 = 0
        self.rectid = None
        self.drawing = False
        self.bounding_boxes = []
        self.object_offset = 0
        self.imagesets = [[], [], []]

        # Create menu bar
        self.menubar = tk.Menu(self.master)
        self.master.config(menu=self.menubar)

        # Create file menu and add to menu bar
        self.fileMenu = tk.Menu(self.menubar, tearoff=0)
        self.fileMenu.add_command(label="Load dataset directory...",
                                  command=self.load_dataset)
        self.fileMenu.add_command(label="Load classifier...",
                                  command=self.load_classifier)
        self.fileMenu.add_separator()
        self.fileMenu.add_command(label="Exit", command=self.quit)
        self.menubar.add_cascade(label="File", menu=self.fileMenu)

        # Create tool menu and add to menu bar
        self.toolMenu = tk.Menu(self.menubar, tearoff=0)
        self.toolMenu.add_command(label="Build dataset...",
                                  command=self.create_builder_window)
        self.menubar.add_cascade(label="Tools", menu=self.toolMenu)

        # Create help menu and add to menu bar
        self.helpMenu = tk.Menu(self.menubar, tearoff=0)
        self.helpMenu.add_command(label="How to use...", command=self.quit)
        self.helpMenu.add_command(label="About...", command=self.quit)
        self.menubar.add_cascade(label="Help", menu=self.helpMenu)

        self.focus_set()
예제 #7
0
파일: ibook.py 프로젝트: zhbi98/ibook
 def __init__(self, menubar=tkinter.Menu(window), configmenubar=window):
     self.menubar = menubar
     self.configmenubar = configmenubar.config(menu=self.menubar)
예제 #8
0
 def hide_menu(self):
     self.emptyMenu = tk.Menu(self.master)
     self.master.config(menu=self.emptyMenu)
예제 #9
0
 def hide_menu_binding(self, event):
     self.emptyMenu = tk.Menu(self.master)
     self.master.config(menu=self.emptyMenu)
예제 #10
0
import tkinter

"""
Menu顶层菜单
"""
win = tkinter.Tk()
win.title("16_Menu_Demo.py By LC")
win.geometry("400x400+200+50")

# 菜单条
menubar = tkinter.Menu(win)
win.config(menu=menubar)


def func():
    print("**********")


def func_python():
    print("I am python")


# 创建一个菜单选项
menu1 = tkinter.Menu(menubar, tearoff=False)

# 给菜单选项添加内容
for item in ['python', 'c', 'java', 'c++', 'c#', 'php', 'B', '退出']:
    if item == '退出':
        # 添加分割线
        menu1.add_separator()
        menu1.add_command(label=item, command=win.quit)
예제 #11
0
 def __init__(self):
     self.main_menu = tkinter.Menu(tearoff=False)
     self._submenus = {}  # {(menu, label): submenu}
     self.get_menu("Help")  # see comments in get_menu()
     self._items = {}  # {path: (menu, index)}
예제 #12
0
    def __init__(self, parent, *args, **kwargs):
        super(FList, self).__init__(parent, *args, **kwargs)

        self.nav_bar = NavBar(self)
        self.nav_bar.pack(side="top", fill="x")
        self.nav_bar.set_cb_go(self.__go_history)
        self.nav_bar.set_cb_root(self.__go_root)
        self.nav_bar.cb_show_info = self.__show_info

        self.__sort_dir = False

        # tree_frame = ttk.Frame(self)
        # tree_frame.pack(side="bottom", expand=True, fill="both")

        columns = (
            'size',
            # 'rights', "owner", "group",
            "ctime",
            # "description",
            # "atime", "mtime"
        )
        self.__tree = ttk.Treeview(self,
                                   show="tree headings",
                                   selectmode='browse',
                                   columns=columns)
        # self.__tree.heading("size", text="Размер", command=lambda c="size": self.__sort(c))
        self.__tree.heading("size", text="Размер")
        # self.__tree.heading("rights", text="Права")
        # self.__tree.heading("owner", text="Владелец")
        # self.__tree.heading("group", text="Группа")
        self.__tree.heading("ctime", text="Создание")
        # self.__tree.heading("description", text="Описание")
        # self.__tree.heading("atime", text="Доступ")
        # self.__tree.heading("mtime", text="Модификация")
        self.__tree.heading('#0', text='Название')

        self.__tree.column("#0", minwidth=200, width=200)
        self.__tree.column("size", minwidth=90, width=90)
        # self.__tree.column("rights", minwidth=40, width=50)
        # self.__tree.column("owner", minwidth=80, width=80)
        # self.__tree.column("group", minwidth=80, width=80)
        self.__tree.column("ctime", minwidth=200, width=200)
        # self.__tree.column("description", minwidth=200, width=200, stretch=False)
        # self.__tree.column("atime", minwidth=90, width=90)
        # self.__tree.column("mtime", minwidth=100, width=100)

        # for c in columns:
        # 	self.__tree.heading(c, text=c, command=lambda c=c: self.__sort(c))

        # #--- horizontal scroll
        # xsb = ttk.Scrollbar(self, orient="horizontal", command= self.__tree.xview)
        # self.__tree['xscroll'] = xsb.set
        # xsb.pack(side="bottom", expand=False, fill="x")

        self.__tree.pack(side="left", expand=True, fill="both")

        #--- vertical scroll
        ysb = ttk.Scrollbar(self, orient="vertical", command=self.__tree.yview)
        self.__tree['yscroll'] = ysb.set
        ysb.pack(side="right", expand=False, fill="y", anchor="e")

        self.__tree.column("#0", width=300)
        self.__tree.tag_bind("simple", "<<TreeviewSelect>>", self.__select_row)
        self.__tree.bind("<Double-1>", self.__open_row)
        # self.__tree.tag_bind("simple", "<<TreeviewOpen>>", self.__open_row)
        self.__tree.bind("<Button-3>", self.__make_cmenu)

        self.cmenu = tkinter.Menu(self, tearoff=0)
        self.cmenu.add_command(label="Свойства",
                               command=self.__show_info,
                               image=ticons.ticon(ticons.INFO),
                               compound="left")
        # self.cmenu.add_command(label="Экспорт", command=self.__show_export, image=ticons.ticon(ticons.I_EXPORT), compound="left")
        self.cmenu.add_command(label="Удалить",
                               command=self.__show_remove,
                               image=ticons.ticon(ticons.TRASH),
                               compound="left")
        # self.cmenu.add_command(label="Изменить", command=self.__show_edit, image=self.__icon_menu_edit, compound="left")

        #--- хранилище
        self.storage = get_storage()

        #--- тек. объекты тома и папки
        self.current_vnode = None
        self.current_fnode = None

        self.modal_about = None

        #--- карта загруженных нод для поиска при событиях от дерева
        self.litems = {}

        # dbus.eon(dbus.SHOW_REMOVE_FTREE_OK, self.__on_ftree_removed)

        #--- signals
        self.signal_file_selected = Signal()  # up signal(FNode)
예제 #13
0
    def initialize(self, x, y):
        self.resizable(0, 0)

        # label vars
        inf_bg = 'lightblue'
        label_font = 'sans-serif'

        # create sensor frames
        self.sensor_frame1 = Tkinter.Frame(
            self,
            height=y,
            width=x,
            bg='white'
        )

        self.sensor_frame2 = Tkinter.Frame(
            self,
            height=y,
            width=x,
            bg='white'
        )

        # initiate first frame
        self.sensor_frame1.grid()

        # lists used for adressing
        frames = [self.sensor_frame1, self.sensor_frame2]
        self.widgets = [[], []]
        self.input_list = [[], []]

        # var for adressing
        self.widget_num = 0

        # add frames to hold widgets
        for frame in frames:
            # create container frames
            graph = Tkinter.Frame(
                frame,
                height=y,
                width=x / 2,
                bg=inf_bg
            )

            variables = Tkinter.Frame(
                frame,
                height=y / 2,
                width=x / 3,
                bg=inf_bg
            )

            information = Tkinter.Frame(
                frame,
                height=y / 2,
                width=x / 3,
                bg=inf_bg
            )

            # place container frames in main frame
            graph.grid(row=0, column=1, rowspan=2, sticky='EW')
            variables.grid(row=1, column=0, sticky='EW')
            information.grid(row=0, column=0, sticky='EW')

            # frames stay same size even with widgets
            graph.grid_propagate(False)
            variables.grid_propagate(False)
            information.grid_propagate(False)

            # list with text used in forloop because it will not change
            labeltekst = ["sensor waarde:", "gemiddeld laatste minuut:", "minimum laatste minuut:",
                          "maximum laatste minuut:"]
            var_labeltekst = ["oprollen bij een waarde van:", "laten zakken bij een waarde van:",
                              "maximale uitrol afstand:", "minimale uitrol afstand:"]

            # add labels
            for i in range(4):
                # text label, text will not change (information frame)
                label = Tkinter.Label(
                    information,
                    text=labeltekst[i],
                    fg='black',
                    bg=inf_bg,
                    font=label_font
                )

                # create variable to change display
                var = Tkinter.StringVar()
                var.set(0)

                # variable label, text changes (information frame)
                val_label = Tkinter.Label(
                    information,
                    textvariable=var,
                    fg='black',
                    bg=inf_bg,
                    font=label_font
                )

                # adding widgets to list for adressing
                self.widgets[self.widget_num].append(var)

                # place labels in the frame
                label.place(x=10, y=40 * (i + 1))
                val_label.place(x=200, y=40 * (i + 1))

                # str_var gebruiken om ingevoerde waarde te lezen
                self.str_var = Tkinter.StringVar(variables, value=0)
                self.str_vars.append(self.str_var)

                # text label, text will not change (variables frame)
                label = Tkinter.Label(
                    variables,
                    text=var_labeltekst[i],
                    fg='black',
                    bg=inf_bg,
                    font=
                    label_font
                )

                # variable entry, text changes to current value (variable frame)
                var_entry = Tkinter.Entry(
                    variables,
                    textvariable=self.str_var
                )

                # buttons to set the values
                button = Tkinter.Button(
                    variables,
                    text="submit",
                    #command=lambda: self.str_var.set(int(var_entry.get()))
                    command=send_min_rollout
                )

                # place the widgets
                label.place(x=10, y=50 * (i) + 20)
                var_entry.place(x=13, y=50 * (i) + 46)
                button.place(x=150, y=50 * (i) + 43)

            # de mooie lijntjes
            labelframe = Tkinter.LabelFrame(information, width=250, height=2)
            labelframe.place(x=10, y=50 * 4 + 35)
            labelframe2 = Tkinter.LabelFrame(information, width=2, height=200)
            labelframe2.place(x=50 * 5 + 47, y=10)
            labelframe2 = Tkinter.LabelFrame(variables, width=2, height=200)
            labelframe2.place(x=50 * 5 + 47, y=10)

            # canvas
            self.canvas = Tkinter.Canvas(graph, width=x / 2 - 25, height=y - 25, bg='white')
            self.canvas.place(x=10, y=10)
            self.canvases.append(self.canvas)

            # create_line(x1,y1,x2,y2)
            self.canvas.create_line(10, y - 35, 10, 10, width=2)
            self.canvas.create_line(10, y - 35, x / 2 - 35, y - 35, width=2)

            # create roster lines
            for q in range(12):
                self.canvas.create_line(10, y - 35 - q * ((x / 2 - 45) / 10), x / 2 - 35,
                                        y - 35 - q * ((x / 2 - 45) / 10))

            for q in range(9):
                self.canvas.create_line(10 + 50 * q, y - 35, 10 + 50 * q, 10)

            self.widget_num += 1

        # add a menu
        self.menu = Tkinter.Menu(self)

        # add a button to menu to show the menu
        self.menu.add_command(label="Hook 1", command=Hook_To_Arduino)
        self.menu.add_command(label="Hook 2", command=Hook_To_Arduino)
        self.menu.add_command(label="Read", command=readserial)
        self.menu.add_command(label="temperature", command=self.show_frame1)
        self.menu.add_command(label="light", command=self.show_frame2)
        self.config(menu=self.menu)
예제 #14
0
    def __menuPrincipal__():
        # ----- Ventana Principal -----
        __ventanaPrincipal__ = tk.Tk()
        __ventanaPrincipal__.iconphoto(
            False, tk.PhotoImage(file='Recursos/store.png'))
        __ventanaPrincipal__.configure(bg=cf)
        __ventanaPrincipal__.geometry(width + "x" + height + '+0+0')
        __ventanaPrincipal__.resizable(width=0, height=0)
        __ventanaPrincipal__.title("It Curo Faciles")
        __ventanaPrincipal__.maxsize(width, height)
        __ventanaPrincipal__.state('zoomed')

        # ----- Opciones bar ------
        menuP = tk.Menu(__ventanaPrincipal__,
                        background=cf,
                        foreground=cl,
                        activebackground=cf,
                        activeforeground=cl,
                        font=(f, 16))

        # ----- subMenú Ventas -----
        ventas = tk.Menu(menuP,
                         tearoff=0,
                         background=cl,
                         foreground=cf,
                         font=(f, 16),
                         activebackground=cf,
                         activeforeground=cl)
        ventas.add_command(label="v1")
        ventas.add_command(label="v2")

        # ----- subMenú Agragaciones -----
        agregaciones = tk.Menu(menuP,
                               tearoff=0,
                               background=cl,
                               foreground=cf,
                               font=(f, 16),
                               activebackground=cf,
                               activeforeground=cl)
        agregaciones.add_command(label="a1", command=None)
        agregaciones.add_command(label="a2", command=None)

        # ----- subMenú actualiza -----
        actualiza = tk.Menu(menuP,
                            tearoff=0,
                            background=cl,
                            foreground=cf,
                            font=(f, 16),
                            activebackground=cf,
                            activeforeground=cl)
        actualiza.add_command(label="ac1", command=None)
        actualiza.add_command(label="ac2", command=None)

        # ----- subMenú consultas -----
        consultas = tk.Menu(menuP,
                            tearoff=0,
                            background=cl,
                            foreground=cf,
                            font=(f, 16),
                            activebackground=cf,
                            activeforeground=cl)
        consultas.add_command(label="c1", command=None)
        consultas.add_command(label="c2", command=None)
        consultas.add_command(label="c3", command=None)

        ayuda = tk.Menu(menuP,
                        tearoff=0,
                        background=cl,
                        foreground=cf,
                        font=(f, 16),
                        activebackground=cf,
                        activeforeground=cl)
        ayuda.add_command(label="Contacto", command=None)

        # ----- Menú principal -----
        menuP.add_cascade(label="Ventas", menu=ventas)
        menuP.add_cascade(label="Agregaciones", menu=agregaciones)
        menuP.add_cascade(label="Actualizaciones", menu=actualiza)
        menuP.add_cascade(label="Consultas", menu=consultas)
        menuP.add_cascade(label="Ayuda", menu=ayuda)

        __ventanaPrincipal__.config(menu=menuP)

        __ventanaPrincipal__.mainloop()
예제 #15
0
import tkinter as tk

root = tk.Tk()


def random():
    print("This is a statement")


mainMenu = tk.Menu(root)
root.configure(menu=mainMenu)
subMenu = tk.Menu(mainMenu)
mainMenu.add_cascade(label="File", menu=subMenu)

subMenu.add_command(label="Random Func", command=random)
subMenu.add_separator()
subMenu.add_command(label="New File", command=random)


root.mainloop()
import tkinter
import ExpressInfo
from tkinter import *
# import time
# import urllib.parse
main_window = tkinter.Tk()  # GUI界面初始化
main_window.title('基于图像识别的快递物流信息跟踪系统')
main_window.iconbitmap('py.ico')
main_window.geometry('600x400')
menubar = tkinter.Menu(main_window)  # 设置菜单栏Exit选项
main_menu = tkinter.Menu(menubar, tearoff=0)
menubar.add_cascade(label='Menu', menu=main_menu)
main_menu.add_command(label='Exit', command=main_window.quit)
main_window.config(menu=menubar)
iscrollbar = Scrollbar(main_window)  # 设置UP滚动条
iscrollbar.place(x=575, y=0, anchor='nw')
iscrollbar.pack(side=RIGHT, ipady=80, anchor='ne')
infolist = Listbox(main_window, yscrollcommand=iscrollbar.set, width=45, height=12)  # 设置UP ListBox
infolist.place(x=255, y=0, anchor='nw')
iscrollbar.config(command=infolist.yview)  # 关联UP滚动条与ListBox
sscrollbar = Scrollbar(main_window)  # 设置DOWN滚动条
sscrollbar.pack(side=RIGHT, ipady=55, anchor='se')
shippinglist = Listbox(main_window, yscrollcommand=sscrollbar.set, width=81, height=9)  # 设置DOWN ListBox
shippinglist.place(x=0, y=230, anchor='nw')
sscrollbar.config(command=shippinglist.yview)  # 关联DOWN滚动条与ListBox
expressinfo = ExpressInfo.ExpressInfo(infolist, shippinglist)  # 实例化ExpressInfo类
upload_button = tkinter.Button(main_window, text='选择图片', font=("宋体", 10, 'bold'), width=10, height=1, command=expressinfo.openfile)  # 设置选择图片按钮并关联相应函数
req_button = tkinter.Button(main_window, text='查询信息', font=("宋体", 10, 'bold'), width=10, height=1, command=expressinfo.req_ocr)  # 设置查询信息按钮并关联相应函数
upload_button.place(x=0, y=205, anchor='nw')
req_button.place(x=160, y=205, anchor='nw')
main_window.mainloop()
예제 #17
0
    def __init__(self):
        # Initial Game Settings
        self._rows = DEFAULT_ROWS
        self._columns = DEFAULT_COLUMNS
        self._first_player = DEFAULT_FIRST_PLAYER
        self._top_left_player = DEFAULT_TOP_LEFT_PLAYER
        self._victory_type = DEFAULT_VICTORY_TYPE

        # Create my othello gamestate here (drawn from the original othello game code)
        self._game_state = othello.OthelloGame(self._rows, self._columns,
                                               self._first_player,
                                               self._top_left_player,
                                               self._victory_type)

        # Initialize all my widgets and window here
        self._root_window = tkinter.Tk()
        self._root_window.configure(background=BACKGROUND_COLOR)
        self._board = othello_models.GameBoard(self._game_state, GAME_WIDTH,
                                               GAME_HEIGHT, self._root_window)
        self._black_score = othello_models.Score(othello.BLACK,
                                                 self._game_state,
                                                 self._root_window)
        self._white_score = othello_models.Score(othello.WHITE,
                                                 self._game_state,
                                                 self._root_window)
        self._player_turn = othello_models.Turn(self._game_state,
                                                self._root_window)

        # Bind my game board with these two events.
        self._board.get_board().bind('<Configure>', self._on_board_resized)
        self._board.get_board().bind('<Button-1>', self._on_board_clicked)
        # self._board.get_board().bind('<Wait>', self._on_board_idle)

        # Create our menu that can be accessed at the top of the GUI
        self._menu_bar = tkinter.Menu(self._root_window)
        self._game_menu = tkinter.Menu(self._menu_bar, tearoff=0)
        self._game_menu.add_command(label='New Game', command=self._new_game)
        self._game_menu.add_command(label='Game Settings',
                                    command=self._configure_game_settings)
        self._game_menu.add_separator()
        self._game_menu.add_command(label='Exit',
                                    command=self._root_window.destroy)
        self._menu_bar.add_cascade(label='Game', menu=self._game_menu)

        # Layout all the widgets here using grid layout
        self._root_window.config(menu=self._menu_bar)
        self._black_score.get_score_label().grid(row=0,
                                                 column=0,
                                                 sticky=tkinter.S)
        self._white_score.get_score_label().grid(row=0,
                                                 column=1,
                                                 sticky=tkinter.S)
        self._board.get_board().grid(row=1,
                                     column=0,
                                     columnspan=2,
                                     padx=50,
                                     pady=10,
                                     sticky=tkinter.N + tkinter.E + tkinter.S +
                                     tkinter.W)
        self._player_turn.get_turn_label().grid(row=2,
                                                column=0,
                                                columnspan=2,
                                                padx=10,
                                                pady=10)

        # Configure the root window's row/column weight (from the grid layout)
        self._root_window.rowconfigure(0, weight=1)
        self._root_window.rowconfigure(1, weight=1)
        self._root_window.rowconfigure(2, weight=1)
        self._root_window.columnconfigure(0, weight=1)
        self._root_window.columnconfigure(1, weight=1)
예제 #18
0
파일: home.py 프로젝트: BatBapt/bank
    def __init__(self, master, perso, database):
        try:
            assert isinstance(perso, person.Person), "Erreur"
            assert isinstance(database, db.Database), "Erreur"
        except AssertionError as e:
            print(e)
            sys.exit(1)

        self.master = master
        self._person = perso
        self.db = database
        self.master.title("Vos comptes")
        tk.Frame.__init__(self, self.master)

        for widget in self.master.winfo_children():
            widget.destroy()

        btn_font = font.Font(family='Helvetica',
                             name='myFont',
                             size=12,
                             weight='bold')

        menu_frame = tk.Frame(self.master, width=850, height=25)
        menu_frame.pack(side=tk.TOP, anchor=tk.W)

        self.add = tk.Menubutton(menu_frame,
                                 text="Ajouter un..",
                                 font=btn_font,
                                 width=20,
                                 borderwidth=2)
        self.add.pack(side=tk.LEFT, fill=tk.X)

        self.add_menu = tk.Menu(self.add, tearoff=0)

        self.menu_widget()

        self.frame = tk.Frame(self.master,
                              width=900,
                              height=475,
                              bg=Home.frame_bg_color)
        self.frame.pack(side=tk.TOP)

        tk.Label(self.frame,
                 text="Bienvenu {}".format(self._person.full_name),
                 bg=Home.frame_bg_color).pack(anchor=tk.NW)
        tk.Label(self.frame,
                 text="Voilà vos comptes: ",
                 bg=Home.frame_bg_color).pack(anchor=tk.NW, pady=(5, 0))

        deco_btn = tk.Button(self.frame,
                             text="Se déconnecter",
                             font=btn_font,
                             command=self.deconnect)
        deco_btn.pack(anchor=tk.NE)

        self.account_frame = tk.Frame(self.frame,
                                      width=450,
                                      height=475,
                                      bg="blue")
        self.account_frame.pack(side=tk.TOP, pady=(10, 0))

        self.benef_frame = tk.Frame(self.frame,
                                    width=450,
                                    height=475,
                                    bg="red")
        self.benef_frame.pack(side=tk.BOTTOM, pady=(10, 0))

        self.account_tab = ttk.Treeview(self.account_frame,
                                        columns=('iban', 'name', 'solde'))

        self.benef_tab = ttk.Treeview(self.benef_frame, columns=('iban'))

        self.display_all_personnal_informations()

        self.account_tab.bind("<Double-1>", self.details)
예제 #19
0
################ Main Window #############################


################ Menu #############################
def hit_me():
    print(
        tk.messagebox._show(
            title='About Tool',
            message=
            'The theory of tool is based on statistical analysis and 3D solved tool result.'
            '\nThe purpose of this tool is to help SI engineer to find out the via impedance more quickly.'
            '\nEngineer saves a lot of time in the sweeping parameter for via optimization.'
        ))


menubar = tk.Menu(window)
filemenu = tk.Menu(menubar, tearoff=0)
menubar.add_cascade(label='File', menu=filemenu)
#filemenu.add_command(label='Save', command='')
filemenu.add_command(label='Exit', command=window.quit)
editmenu = tk.Menu(menubar, tearoff=0)
menubar.add_cascade(label='Help', menu=editmenu)
editmenu.add_command(label='About Tool', command=hit_me)
window.config(menu=menubar)

################ Menu #############################


################ Import picture #############################
def rc(relative_path):
    if hasattr(sys, '_MEIPASS'):
예제 #20
0
파일: scratch.py 프로젝트: geofstone/pylcg
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        # tk.Tk.iconbitmap(self, default='clienticon.ico')  # must be an icon file
        tk.Tk.wm_title(self, 'This is the window title')

        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        # Build menu bar:
        menubar = tk.Menu(container)
        filemenu = tk.Menu(menubar, tearoff=0)
        filemenu.add_command(
            label='Save settings',
            command=lambda: popupmsg('Not supported just yet.'))
        filemenu.add_separator()
        filemenu.add_command(label='Exit', command=quit)
        menubar.add_cascade(label='File', menu=filemenu)
        exchangeChoice = tk.Menu(menubar, tearoff=1)
        exchangeChoice.add_command(
            label='BTC-e', command=lambda: changeExchange('BTC-e', 'btce'))
        exchangeChoice.add_command(
            label='Bitfinex',
            command=lambda: changeExchange('Bitfinex', 'bitfinex'))
        exchangeChoice.add_command(
            label='Bitstamp',
            command=lambda: changeExchange('Bitstamp', 'bitstamp'))
        exchangeChoice.add_command(
            label='Huobi', command=lambda: changeExchange('Huobi', 'huobi'))
        menubar.add_cascade(label='Exchange', menu=exchangeChoice)
        dataTF = tk.Menu(menubar, tearoff=1)
        dataTF.add_command(label='Tick',
                           command=lambda: changeTimeFrame('tick'))
        dataTF.add_command(label='1 Day',
                           command=lambda: changeTimeFrame('1d'))
        dataTF.add_command(label='3 Day',
                           command=lambda: changeTimeFrame('3d'))
        dataTF.add_command(label='1 Week',
                           command=lambda: changeTimeFrame('7d'))
        menubar.add_cascade(label='Data Time Frame', menu=dataTF)
        OHLCI = tk.Menu(menubar, tearoff=1)
        OHLCI.add_command(label='Tick',
                          command=lambda: changeTimeFrame('tick'))
        OHLCI.add_command(label='1 Minute',
                          command=lambda: changeSampleSize('1Min', 0.0005))
        OHLCI.add_command(label='5 Minute',
                          command=lambda: changeSampleSize('5Min', 0.003))
        OHLCI.add_command(label='15 Minute',
                          command=lambda: changeSampleSize('15Min', 0.008))
        OHLCI.add_command(label='30 Minute',
                          command=lambda: changeSampleSize('30Min', 0.016))
        OHLCI.add_command(label='1 Hour',
                          command=lambda: changeSampleSize('1H', 0.032))
        OHLCI.add_command(label='3 Hour',
                          command=lambda: changeSampleSize('3H', 0.096))
        menubar.add_cascade(label='OHLC Interval', menu=OHLCI)
        topIndi = tk.Menu(menubar, tearoff=1)
        topIndi.add_command(label='None',
                            command=lambda: addTopIndicator('none'))
        topIndi.add_command(label='RSI',
                            command=lambda: addTopIndicator('rsi'))
        topIndi.add_command(label='MACD',
                            command=lambda: addTopIndicator('macd'))
        menubar.add_cascade(label='Top Indicator', menu=topIndi)
        mainIndi = tk.Menu(menubar, tearoff=1)
        mainIndi.add_command(label='None',
                             command=lambda: addMiddleIndicator('none'))
        mainIndi.add_command(label='SMA',
                             command=lambda: addMiddleIndicator('sma'))
        mainIndi.add_command(label='EMA',
                             command=lambda: addMiddleIndicator('ema'))
        menubar.add_cascade(label='Main/middle Indicator', menu=mainIndi)
        bottomIndi = tk.Menu(menubar, tearoff=1)
        bottomIndi.add_command(label='None',
                               command=lambda: addBottomIndicator('none'))
        bottomIndi.add_command(label='RSI',
                               command=lambda: addBottomIndicator('rsi'))
        bottomIndi.add_command(label='MACD',
                               command=lambda: addBottomIndicator('macd'))
        menubar.add_cascade(label='Bottom Indicator', menu=bottomIndi)
        tradeButton = tk.Menu(menubar, tearoff=1)
        tradeButton.add_command(label='Manual Trading',
                                command=lambda: popupmsg('Not live yet.'))
        tradeButton.add_command(label='Automated Trading',
                                command=lambda: popupmsg('Not live yet.'))
        tradeButton.add_separator()
        tradeButton.add_command(label='Quick Buy',
                                command=lambda: popupmsg('Not live yet.'))
        tradeButton.add_command(label='Quick Sell',
                                command=lambda: popupmsg('Not live yet.'))
        tradeButton.add_separator()
        tradeButton.add_command(label='Set up Quick Buy/Sell',
                                command=lambda: popupmsg('Not live yet.'))
        menubar.add_cascade(label='Trading', menu=tradeButton)
        startStop = tk.Menu(menubar, tearoff=1)
        startStop.add_command(label='Resume',
                              command=lambda: loadChart('start'))
        startStop.add_command(label='Pause', command=lambda: loadChart('stop'))
        menubar.add_cascade(label='Resume/Pause client', menu=startStop)
        helpmenu = tk.Menu(menubar, tearoff=0)
        helpmenu.add_command(label='Tutorial', command=tutorial)
        menubar.add_cascade(label='Help', menu=helpmenu)

        tk.Tk.config(self, menu=menubar)

        # Build dict of frames:
        self.frames = {}
        for F in (StartPage, PageOne, BTCe_Page):
            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame(StartPage)
예제 #21
0
파일: ibook.py 프로젝트: zhbi98/ibook
    def fileMenu(self):
        fileoption = tkinter.Menu(self.menubar, tearoff=0)
        fileoption.add_command(label=file[1],
                               accelerator="Ctrl+N",
                               command=FileOperation.newFile,
                               font=(Font.fontFace()))
        fileoption.add_command(label=file[2],
                               accelerator="Ctrl+Z",
                               command=AskDialog.openDialog,
                               font=(Font.fontFace()))
        fileoption.add_command(label=file[3],
                               accelerator="Ctrl+S",
                               command=FileOperation.saveFile,
                               font=(Font.fontFace()))
        fileoption.add_command(label=file[4],
                               command=FileOperation.saveAsFile,
                               font=(Font.fontFace()))

        saveencode = tkinter.Menu(fileoption, tearoff=0)
        saveencode.add_checkbutton(label=code[0], font=(Font.fontFace()))
        saveencode.add_checkbutton(label=code[1], font=(Font.fontFace()))
        saveencode.add_checkbutton(label=code[2], font=(Font.fontFace()))
        saveencode.add_checkbutton(label=code[3], font=(Font.fontFace()))
        saveencode.add_checkbutton(label=code[4], font=(Font.fontFace()))
        saveencode.add_checkbutton(label=code[5], font=(Font.fontFace()))
        saveencode.add_separator()
        saveencode.add_checkbutton(label=code[6], font=(Font.fontFace()))
        saveencode.add_checkbutton(label=code[7], font=(Font.fontFace()))
        saveencode.add_checkbutton(label=code[8], font=(Font.fontFace()))
        saveencode.add_checkbutton(label=code[9], font=(Font.fontFace()))
        saveencode.add_checkbutton(label=code[10], font=(Font.fontFace()))
        saveencode.add_checkbutton(label=code[11], font=(Font.fontFace()))
        saveencode.add_separator()
        saveencode.add_checkbutton(label=code[12], font=(Font.fontFace()))
        saveencode.add_checkbutton(label=code[13], font=(Font.fontFace()))
        saveencode.add_separator()
        saveencode.add_checkbutton(label=code[14], font=(Font.fontFace()))
        saveencode.add_checkbutton(label=code[15], font=(Font.fontFace()))
        saveencode.add_separator()
        saveencode.add_checkbutton(label=code[16], font=(Font.fontFace()))

        fileoption.add_cascade(label=file[5],
                               font=(Font.fontFace()),
                               menu=saveencode)

        fileoption.add_command(label=file[6],
                               command=FileOperation.closeFile,
                               font=(Font.fontFace()))
        fileoption.add_separator()
        fileoption.add_command(label=file[7],
                               command=message.MessageBox.printMessage,
                               font=(Font.fontFace()))

        fileoption.add_command(label=file[8],
                               accelerator="Ctrl+P",
                               command=message.MessageBox.printMessage,
                               font=(Font.fontFace()))

        fileoption.add_separator()
        fileoption.add_command(label=file[9],
                               command=message.MessageBox.exitMessage,
                               font=(Font.fontFace()))

        self.menubar.add_cascade(label=file[0],
                                 menu=fileoption,
                                 font=(Font.fontFace()))
예제 #22
0
import tkinter as tk  #window create hoga esse
from tkinter import ttk
from tkinter import font, colorchooser, filedialog, messagebox
import os  #for read, write, save files or data

main_application = tk.Tk()
main_application.geometry("800x800")  #Size k liya
main_application.title("Apni Notepad")  #Opening Window ka size

main_menu = tk.Menu()  # ye humara MAIN MENU HAI

#ICONS ICONS ICONS ICONS ICONS

new_icon = tk.PhotoImage(file="Icons/new.png")
open_icon = tk.PhotoImage(file="Icons/open.png")
save_icon = tk.PhotoImage(file="Icons/save.png")
saveas_icon = tk.PhotoImage(file="Icons/save-as.png")
exit_icon = tk.PhotoImage(file="Icons/exit.png")

copy_icon = tk.PhotoImage(file="Icons/copy.png")
paste_icon = tk.PhotoImage(file="Icons/paste.png")
cut_icon = tk.PhotoImage(file="Icons/cut.png")

tool_bar = tk.PhotoImage(file="Icons/tool-box.png")
status_bar = tk.PhotoImage(file="Icons/view.png")

dark_theme = tk.PhotoImage(file="Icons/oval.png")
light_theme = tk.PhotoImage(file="Icons/dry-clean.png")

#Creating Sub-Menus
file = tk.Menu(main_menu,
예제 #23
0
def main():
    """Creates and blocks on the GUI tool for labeling image datasets."""

    ############################################################################
    # Program and GUI Setup
    #
    # This sets up variables to hold the working state of the program.
    # This sets up the windows, frames, and menus but does not populate them.
    # Areas are populated as their functionality is defined.
    ############################################################################
    data = Dataset()

    # This is the outline user is currently tracing.
    outline = []  # List of (x,y) coordinates
    outline_ids = []  # Handles to the canvas polygon objects.

    # This is how far zoomed in/out the user currently is, size multiplier.
    scale = .25

    root = tk.Tk()
    root.wm_title("Label Tool")

    menu_bar = tk.Menu(root)
    root.config(menu=menu_bar)

    file_menu = tk.Menu(menu_bar, tearoff=0)
    menu_bar.add_cascade(label="File", menu=file_menu)

    edit_menu = tk.Menu(menu_bar, tearoff=0)
    menu_bar.add_cascade(label="Edit", menu=edit_menu)

    view_menu = tk.Menu(menu_bar, tearoff=0)
    menu_bar.add_cascade(label="View", menu=view_menu)

    help_menu = tk.Menu(menu_bar, tearoff=0)
    menu_bar.add_cascade(label="Help", menu=help_menu)

    ############################################################################
    # File Menu
    ############################################################################
    def load_dataset_callback(path=None):
        if path is None:
            path = tkinter.filedialog.askdirectory()
        if not path:
            return
        data.load_dataset(path)
        redraw_canvas()
        update_label_options()

    file_menu.add_command(label="Open Dataset", command=load_dataset_callback)

    def delete_image_callback(dc=None):
        resp = tkinter.messagebox.askokcancel(
            title='Remove Image',
            message=
            'This will move the current image to the trash can.  Procede?',
        )
        if resp:
            data.delete_current_image()
            redraw_canvas()

    file_menu.add_command(label='Delete Image', command=delete_image_callback)

    def discard_labeled_callback(dc=None):
        data.discard_labeled_data()

    file_menu.add_command(label='Discard Labeled',
                          command=discard_labeled_callback)

    file_menu.add_separator()
    file_menu.add_command(label="Exit",
                          command=root.quit,
                          accelerator='Alt-F4')

    ############################################################################
    # Edit Menu
    ############################################################################
    def add_label_dialog():
        dialog = tk.Toplevel()
        dialog.wm_title("Add Label")
        # Entry is where user types in their new label
        entry = tk.Entry(dialog)

        def entry_callback(dc=None):
            label = entry.get()
            if label and data.path:
                data.add_label_type(label)
                dialog.destroy()
                update_label_options()

        p = 4  # Padding
        entry.grid(row=0, columnspan=2, sticky='NESW', padx=p, pady=p)
        entry.focus_set()
        entry.bind("<Return>", entry_callback)
        entry.bind("<Escape>", lambda dc: dialog.destroy())

        # OK and CANCEL buttons
        ok = tk.Button(dialog, text='Ok', command=entry_callback)
        ok.grid(row=1, column=0)
        cancel = tk.Button(dialog, text='Cancel', command=dialog.destroy)
        cancel.grid(row=1, column=1)
        root.wait_window(dialog)

    edit_menu.add_command(label='Add Label Type', command=add_label_dialog)

    def unlabel_selection(event=None):
        """Label the current selection as 'unlabeled'"""
        data.add_label_outline('unlabeled', outline)
        cancel_draw()  # Removes the outline
        draw_labels()  # Redraws the label image

    edit_menu.add_command(label='Unlabel',
                          command=add_label_dialog,
                          accelerator='u')
    root.bind("u", unlabel_selection)
    root.bind("U", unlabel_selection)

    ############################################################################
    # View Menu
    ############################################################################
    def prev_image_callback(dont_care=None):
        data.prev_image()  # Updates the database controller
        redraw_canvas()

    view_menu.add_command(label='Previous Image',
                          command=prev_image_callback,
                          accelerator='<-')
    root.bind("<Left>", prev_image_callback)

    def next_image_callback(dont_care=None):
        data.next_image()  # Updates the database controller
        redraw_canvas()

    view_menu.add_command(label='Next Image',
                          command=next_image_callback,
                          accelerator='->')
    root.bind("<Right>", next_image_callback)

    view_menu.add_separator()

    def zoom_in_callback(dontcare=None):
        nonlocal scale
        scale *= 1.25
        redraw_canvas()

    view_menu.add_command(label='Zoom in',
                          command=zoom_in_callback,
                          accelerator='+')
    root.bind("=", zoom_in_callback)
    root.bind("+", zoom_in_callback)

    def zoom_out_callback(dontcare=None):
        nonlocal scale
        scale /= 1.25
        redraw_canvas()

    view_menu.add_command(label='Zoom out',
                          command=zoom_out_callback,
                          accelerator='-')
    root.bind("-", zoom_out_callback)
    root.bind("_", zoom_out_callback)

    view_menu.add_separator()

    # These control how the existing labels are displayed to the user.
    view_label_outline = tk.BooleanVar()
    view_label_infill = tk.BooleanVar()
    view_label_outline.set(True)
    view_label_infill.set(True)
    view_menu.add_checkbutton(label='Outline Labels',
                              variable=view_label_outline)
    view_menu.add_checkbutton(label='Infill Labels',
                              variable=view_label_infill)

    ############################################################################
    # Help Menu
    ############################################################################
    def show_statistics_callback(dontcare=None):
        # TODO: help button
        #           * explain how to correctly label the objects
        #           * list all keyboard shortcuts
        title = "Dataset Labeling Statistics"
        message = data.statistics()
        root.option_add('*Dialog.msg.font', 'Courier 14')
        tkinter.messagebox.showinfo(title, message)
        root.option_clear()

    help_menu.add_command(label='Statistics', command=show_statistics_callback)

    def help_menu_callback(dontcare=None):
        title = "Help"
        message = []
        message.append("TODO, Topics:")
        message.append("")
        message.append("Open Dataset")
        message.append("")

        message.append("File: Discard Labeled")
        discard = "This temporarily discards images which already have labels. "
        discard += "Restart this program to see the full set of images again."
        message.append(discard)
        message.append("")

        message.append("Add Label Type")
        message.append("Outline Tool")
        message.append("Floodfill Tool")
        message.append("Cancel and Complete")
        message.append("")

        message.append("How to label:")
        instructions = "The dataset tools use many random point samples drawn from the label image. "
        instructions += "Labels don't need to be perfectly accurate but their area should correspond "
        instructions += "to the object's area and should mostly line up.  Small specs of missing or "
        instructions += "incorrect labels are insignificant if most of the image is well labeled.  "
        message.append(instructions)
        tkinter.messagebox.showinfo(title, '\n'.join(message))

    help_menu.add_command(label='Help', command=help_menu_callback)

    ############################################################################
    # Make the image editing window
    ############################################################################
    canvas_frame = tk.Frame(root)
    canvas_frame.grid(row=1, columnspan=3, sticky='NESW')
    root.grid_columnconfigure(0, weight=1)
    root.grid_rowconfigure(1, weight=1)

    canvas = tk.Canvas(canvas_frame,
                       borderwidth=5,
                       relief="ridge",
                       cursor='crosshair')
    canvas.grid(row=0, column=0, sticky='NESW')
    canvas_frame.grid_columnconfigure(0, weight=1)
    canvas_frame.grid_rowconfigure(0, weight=1)

    # Horizontal and Vertical scrollbars
    xscrollbar = tk.Scrollbar(canvas_frame, orient=tk.HORIZONTAL)
    xscrollbar.grid(row=1, column=0, sticky='SEW')
    xscrollbar.config(command=canvas.xview)
    canvas.config(xscrollcommand=xscrollbar.set)
    yscrollbar = tk.Scrollbar(canvas_frame, orient=tk.VERTICAL)
    yscrollbar.grid(row=0, column=1, sticky='ENS')
    yscrollbar.config(command=canvas.yview)
    canvas.config(yscrollcommand=yscrollbar.set)

    # Right mouse button drags the canvas around under the mouse.
    # This way the user don't need to use the scroolbars.
    canvas.bind("<Button-3>", lambda event: canvas.scan_mark(event.x, event.y))
    canvas.bind("<B3-Motion>",
                lambda event: canvas.scan_dragto(event.x, event.y, gain=1))

    def cancel_draw(event=None):
        """Discards whatever the user is currently drawing on the canvas."""
        outline.clear(
        )  # Clear the internal storage for the in-progress outline
        # Clear the outline from the screen
        for poly_id in outline_ids:
            canvas.delete(poly_id)
        outline_ids.clear()
        # Cancel the floodfill tool.
        nonlocal floodfill_mask
        floodfill_mask = None

    # cancel_button = tk.Button(toolbar, text='Cancel', command=cancel_draw)
    # cancel_button.grid(row=0, column=tb_col); tb_col += 1
    edit_menu.add_command(label='Cancel',
                          command=cancel_draw,
                          accelerator='Escape')
    root.bind("<Escape>", cancel_draw)

    def draw_image():
        """
        Clears the canvas and draws the current image as the background
        """
        cancel_draw()
        canvas.delete(tk.ALL)
        image = Image.open(data.current_image)
        # Rescale the image
        new_size = tuple(int(round(coord * scale)) for coord in image.size)
        image = image.resize(new_size, Image.ANTIALIAS)
        photo = ImageTk.PhotoImage(image)
        canvas.create_image((0, 0), image=photo, anchor='nw')
        canvas._photo_ = photo  # Save image from garbage collection
        canvas._image_ = image  # Save image from garbage collection
        canvas.config(scrollregion=canvas.bbox(tk.ALL))

    def draw_labels(*args):
        draw_labels_infill()
        draw_labels_outline()

    # Redraw the labels layer everytime the user changes its settings.
    view_label_outline.trace('w', draw_labels)
    view_label_infill.trace('w', draw_labels)

    def draw_labels_infill():
        """Draws the labels over the canvas as a semi transparent layer."""
        # Delete any existing label layer before redrawing it.
        label_layer_id = getattr(canvas, '_lbl_layer_', None)
        if label_layer_id is not None:
            canvas.delete(label_layer_id)
            canvas._lbl_layer_ = None

        if view_label_infill.get():
            label = Image.open(data.current_label)
            # Rescale the label image
            new_size = tuple(int(round(coord * scale)) for coord in label.size)
            label = label.resize(new_size, Image.NEAREST)
            label = np.asarray(label)
            # Make The labels channel semi-transparent.   The label 0 is reserved
            # for unlabeled areas, make these areas fully  transparent
            # (alpha = 0).
            alpha = np.empty(label.shape[:2], dtype=np.uint8)
            alpha.fill(96)
            alpha[np.sum(label, axis=2) == 0] = 0
            # TODO: Map the label-colors to high-visibility colors
            pass
            # Cast back to PIL
            pil_label = label[..., :3]
            pil_label = Image.frombuffer('RGBA', new_size,
                                         np.dstack([pil_label, alpha]), 'raw',
                                         'RGBA', 0, 1)
            # Display the label layer
            photo = ImageTk.PhotoImage(pil_label)
            layer = canvas.create_image((0, 0), image=photo, anchor='nw')
            canvas._lbl_photo_ = photo  # Save image from garbage collection
            canvas._label_ = pil_label  # Save image from garbage collection
            canvas._lbl_layer_ = layer
            canvas.config(scrollregion=canvas.bbox(tk.ALL))

    def draw_labels_outline():
        """Draws the outlines of the labels over the canvas."""
        # Delete any existing label outlines first.
        label_outlines = getattr(canvas, '_lbl_outline_', [])
        for poly_id in label_outlines:
            canvas.delete(poly_id)
        canvas._lbl_outline_ = []

        if view_label_outline.get():
            cur_lbl = label_options.curselection()
            if not cur_lbl:
                # Silently fail if the user hasn't selected a label type to outline.
                return
            labels = np.array(Image.open(data.current_label), dtype=np.uint8)
            if labels.shape[2] != 4:
                # Label image missing alpha channel, outlines will not work.
                return
            selected_label = np.all(labels == label_color(),
                                    axis=2)  # Compare all color components
            selected_label = np.array(
                selected_label, dtype=np.uint8)  # Cast to uint8 for OpenCV
            x, contours, hierarchy = cv2.findContours(selected_label,
                                                      cv2.RETR_LIST,
                                                      cv2.CHAIN_APPROX_SIMPLE)
            for edge in contours:
                edge = edge.reshape(-1, 2)
                scaled_coords = [(c0 * scale, c1 * scale) for c0, c1 in edge]
                edge_id = canvas.create_polygon(scaled_coords,
                                                outline='black',
                                                width=1,
                                                fill='')
                canvas._lbl_outline_.append(edge_id)

    def redraw_canvas():
        draw_image()
        draw_labels()

    def draw_outline():
        """Redraws the current outline."""
        for poly_id in outline_ids:
            canvas.delete(poly_id)
        outline_ids.clear()
        if len(outline) > 0:
            scaled_coords = [(c0 * scale, c1 * scale) for c0, c1 in outline]
            neon_green = "#39FF14"
            outline_ids.append(
                canvas.create_polygon(scaled_coords,
                                      outline=neon_green,
                                      width=3,
                                      fill=''))
            outline_ids.append(
                canvas.create_polygon(scaled_coords,
                                      outline='black',
                                      width=1,
                                      fill=''))

    def draw_outline_callback(event):
        """
        Callback for when user is drawing a label around an object in the image.
        User left clicks to drop a vertex of a polygon which circles the object.
            OR
        User holds down left mouse button and circles the object.
        """
        canvas_x = canvas.canvasx(event.x) / scale
        canvas_y = canvas.canvasy(event.y) / scale
        coords = (canvas_x, canvas_y)
        # Don't include duplicate coordinates
        if not outline or outline[-1] != coords:
            outline.append(coords)
        draw_outline()

    canvas.bind("<Button-1>", draw_outline_callback)
    canvas.bind("<B1-Motion>", draw_outline_callback)

    # Variable holding the mask for the current flood fill operation.
    floodfill_mask = None

    def floodfill(dontcare=None):
        """
        This applies the flood fill algorithm and saves the output as 
        floodfill_mask.  This also calls draw_floodfill to display it to user
        for confirmation.
        """
        if label_color() is None:
            return

        if label_color == (0, 0, 0, 0):
            tkinter.messagebox.showwarning(
                title='Select a label',
                message='Floodfill unlabeled is not what you wanted.',
            )
            return

        # Pressing the 'f' key will confirm a pending floodfill operation.
        # This way the user can spam the 'f' key and get multiple iterations
        # of floodfill.
        apply_floodfill()

        # Retrieve the data for the current image
        image = np.array(Image.open(data.current_image))
        label_image = np.array(Image.open(data.current_label))
        # Initialize the mask to possible background.
        mask = np.zeros(image.shape[:2], dtype=np.uint8)
        mask.fill(cv2.GC_PR_BGD)
        # Mark all areas with the current label as foreground.
        # This compares color components, then checks all components in each pixel.
        assert (label_image.shape[2] == 4)
        foreground = np.all(label_image == label_color(), axis=2)
        mask[foreground] = cv2.GC_FGD
        # Mark all areas with a different label as background
        labeled_areas = np.any(label_image, axis=2)
        background = np.logical_and(np.logical_not(foreground), labeled_areas)
        mask[background] = cv2.GC_BGD
        #
        iterCount = 1
        mode = cv2.GC_INIT_WITH_MASK
        bgdModel = np.zeros((1, 65), np.float64)
        fgdModel = np.zeros((1, 65), np.float64)
        mask, bgdModel, fgdModel = cv2.grabCut(image,
                                               mask, (0, 0, 1, 1),
                                               bgdModel=bgdModel,
                                               fgdModel=fgdModel,
                                               iterCount=iterCount,
                                               mode=mode)
        # Find the outline of the foreground segment
        foreground = np.logical_or((mask == cv2.GC_FGD),
                                   (mask == cv2.GC_PR_FGD))
        # Save the floodfill for once the user has confirmed it.
        nonlocal floodfill_mask
        floodfill_mask = np.array(foreground, dtype=np.bool)
        draw_floodfill()

    def draw_floodfill():
        assert (floodfill_mask is not None)

        # Show the suggested labeling to the user.
        ff_color = np.array(label_color()[:3] + (0, ), dtype=np.uint8)
        ff_display = np.broadcast_to(ff_color,
                                     floodfill_mask.shape[:2] + (4, ))
        ff_display = np.array(ff_display, dtype=np.uint8,
                              order='C')  # Broadcast is lazy.
        ff_display[floodfill_mask, 3] += 128

        true_size = tuple(reversed(ff_display.shape[:2]))
        ff_pil = Image.frombuffer('RGBA', true_size, ff_display, 'raw', 'RGBA',
                                  0, 1)
        new_size = tuple(int(round(dim * scale)) for dim in ff_pil.size)
        ff_pil = ff_pil.copy().resize(new_size, Image.NEAREST)
        ff_photo = ImageTk.PhotoImage(ff_pil)
        ff_layer = canvas.create_image((0, 0), image=ff_photo, anchor='nw')
        canvas._ff_pil_ = ff_pil  # Save image from garbage collection
        canvas._ff_photo_ = ff_photo  # Save image from garbage collection
        # Put the layer ID where cancle_draw() will find it.
        outline_ids.append(ff_layer)

        # Draw an outline around the newly labeled areas
        mask_copy = np.array(floodfill_mask, dtype=np.uint8)
        x, contours, hierarchy = cv2.findContours(mask_copy, cv2.RETR_LIST,
                                                  cv2.CHAIN_APPROX_SIMPLE)
        for edge in contours:
            edge = edge.reshape(-1, 2)
            scaled_coords = [(c0 * scale, c1 * scale) for c0, c1 in edge]
            edge_id = canvas.create_polygon(scaled_coords,
                                            outline='black',
                                            width=1,
                                            fill='')
            outline_ids.append(edge_id)

    def apply_floodfill():
        """
        Applies the current flood fill suggestion, stored in floodfill_mask.
        Writes the new labels to file, clears the floodfill operation, and 
        redraws new labels.

        If there is no pending floodfill operation, this silently does nothing.
        """
        nonlocal floodfill_mask
        label = label_color()
        if floodfill_mask is not None and label is not None:
            data.add_label_mask(label, floodfill_mask)
            floodfill_mask = None  # Discards the (now written) flood fill data
            cancel_draw()  # Removes the outline
            draw_labels()  # Redraws the label image

    edit_menu.add_command(label='Floodfill',
                          command=floodfill,
                          accelerator='f')
    root.bind("f", floodfill)
    root.bind("F", floodfill)

    def finish_polygon(event=None):
        # Look up the current label
        lbl = label_color()
        if lbl is None:
            return  # No label selected, do nothing.

        apply_floodfill()

        # This polygon to the label image
        data.add_label_outline(lbl, outline)
        cancel_draw()  # Removes the outline
        draw_labels()  # Redraws the label image

    edit_menu.add_command(label='Complete',
                          command=finish_polygon,
                          accelerator='Enter/Space')
    root.bind("<space>", finish_polygon)
    root.bind("<Return>", finish_polygon)

    ##########################################
    # Show a list of available labels.
    ##########################################
    label_options = tk.Listbox(root)
    label_options.grid(row=1, column=3, sticky='NESW')

    def update_label_options():
        # Insert the labels into the list
        label_options_entries = label_options.get(0, tk.END)
        labels = data.names.values(
        )  # dataset updates its names dict when the entry is added.
        labels = sorted(labels)  # Sort labels alphabetically
        if 'unlabeled' in labels:  # Bump special entry 'unlabeled' to top of list
            labels.remove('unlabeled')
            labels.insert(0, 'unlabeled')
        for index, label in enumerate(labels):
            if label not in label_options_entries:  # Don't make duplicate entries
                label_options.insert(index, label)
                label_options.itemconfig(index, {'bg': 'white', 'fg': 'black'})

    def label_color():
        """Look up the current labels color. Returns None if no label selected."""
        label = label_options.curselection()
        if not label:  # No label selected.
            tkinter.messagebox.showwarning(
                title='No Label Selected',
                message=
                'Please select a label from the list on the right or add a new one with the "Add Label" button.',
            )
            return None
        label_name = label_options.get(
            label)  # listbox widget returns index into itself...
        return next(color for color, name in data.names.items()
                    if name == label_name)

    # load_dataset_callback('.')
    root.mainloop()
예제 #24
0
    def __init__(self):
        self.ventana = tk.Tk()
        self.ventana.title("Metrómono")

        self.bpm_seleccionado = tk.IntVar()  # BPMs recogidos de entrada_bpm
        self.nota_seleccionada = tk.StringVar()  # Nota elegida para el tono
        self.compas_seleccionado = tk.IntVar()  # Compás elegido

        # Carga de valores iniciales
        self.configuracion = Archivo_config(ARCHIVO_CONFIG)
        self.nota_seleccionada.set(self.configuracion.nota)
        self.bpm_seleccionado.set(self.configuracion.bpm)
        self.compas_seleccionado.set(self.configuracion.compas)
        self.sonando = False
        self.seguir_abierto = True

        self.boton_tap = tk.Button(self.ventana,
                                   text="TAP",
                                   command=self.tapping,
                                   activebackground="cyan")
        self.t1 = 0
        self.t2 = 0

        # Menú totalmente inncecesario pero que hago porque puedo
        self.barra_menu = tk.Menu(self.ventana)
        self.menu_archivo = tk.Menu(self.barra_menu, tearoff=0)
        self.menu_archivo.add_command(label="Salir", command=self.guardado)
        self.menu_ayuda = tk.Menu(self.barra_menu, tearoff=0)
        self.menu_ayuda.add_command(label="Ayuda", command=self.ayuda)
        self.menu_ayuda.add_command(label="Atajos de teclado",
                                    command=self.ayuda_atajos)
        self.menu_ayuda.add_command(label="Licencia", command=self.licencia)
        self.menu_ayuda.add_separator()  # Barra horizontal
        self.menu_ayuda.add_command(label="Acerca de Metrómono",
                                    command=self.acerca_de)
        self.barra_menu.add_cascade(label="Archivo", menu=self.menu_archivo)
        self.barra_menu.add_cascade(label="Ayuda", menu=self.menu_ayuda)

        # Contiene el recolector de BPMs y el botón de inicio/pausa
        self.frame_superior = tk.Frame(self.ventana)

        self.deslizable_bpm = tk.Scale(self.frame_superior,
                                       variable=self.bpm_seleccionado,
                                       orient=tk.HORIZONTAL,
                                       from_=BPM_MINIMO,
                                       to=BPM_MAXIMO,
                                       activebackground="cyan",
                                       length=120)
        self.etiqueta_bpm = tk.Label(self.frame_superior,
                                     text="BPMs")  # Label indicando "bpms"

        self.boton = tk.Button(self.frame_superior,
                               text="Iniciar",
                               command=self.accion_boton,
                               activebackground="cyan")

        self.desplegable_notas = ttk.Combobox(
            self.ventana,
            textvariable=self.nota_seleccionada,
            width=1,
            values=list(FRECUENCIAS.keys()))

        # Contiene el radiobutton con los compases
        self.frame_compas = tk.Frame(self.ventana)

        self.no_compas = tk.Radiobutton(self.frame_compas,
                                        text="Sin compás",
                                        variable=self.compas_seleccionado,
                                        value=0)
        self.compas_2_4 = tk.Radiobutton(self.frame_compas,
                                         text="2/4",
                                         variable=self.compas_seleccionado,
                                         value=2)
        self.compas_3_4 = tk.Radiobutton(self.frame_compas,
                                         text="3/4",
                                         variable=self.compas_seleccionado,
                                         value=3)
        self.compas_4_4 = tk.Radiobutton(self.frame_compas,
                                         text="4/4",
                                         variable=self.compas_seleccionado,
                                         value=4)
예제 #25
0
 def _createHelpMenu(self, menuBar):
     helpMenu = tkinter.Menu(menuBar)
     helpMenu.add_command(label = 'Help', command = self._onHelpHelp)
     helpMenu.add_command(label = 'About...', command = self._onHelpAbout)
     menuBar.add_cascade(label = 'Help', menu = helpMenu)
예제 #26
0
    def create_widgets(self):
        toplevel_frame = ttk.Frame(self, padding='0.1i')

        (self.toolslist, selected_item) = self.get_tools_list()
        self.tools_frame = ttk.LabelFrame(toplevel_frame,
                                          text="{} Available Tools".format(
                                              len(self.toolslist)),
                                          padding='0.1i')
        self.toolnames = tk.StringVar(value=self.toolslist)
        self.tools_listbox = tk.Listbox(self.tools_frame,
                                        height=22,
                                        listvariable=self.toolnames)
        self.tools_listbox.bind("<<ListboxSelect>>", self.update_tool_help)
        self.tools_listbox.grid(row=0, column=0, sticky=tk.NSEW)
        self.tools_listbox.columnconfigure(0, weight=10)
        self.tools_listbox.rowconfigure(0, weight=1)
        s = ttk.Scrollbar(self.tools_frame,
                          orient=tk.VERTICAL,
                          command=self.tools_listbox.yview)
        s.grid(row=0, column=1, sticky=(tk.N, tk.S))
        self.tools_listbox['yscrollcommand'] = s.set
        self.tools_frame.grid(row=0, column=0, sticky=tk.NSEW)
        self.tools_frame.columnconfigure(0, weight=10)
        self.tools_frame.columnconfigure(1, weight=1)
        self.tools_frame.rowconfigure(0, weight=1)

        overall_frame = ttk.Frame(toplevel_frame, padding='0.1i')

        # json_str = '{"default_value": null, "description": "Directory containing data files.", "flags": ["--wd"], "name": "Working Directory", "optional": true, "parameter_type": "Directory"}'
        # self.wd = FileSelector(json_str, overall_frame)
        # self.wd.grid(row=0, column=0, sticky=tk.NSEW)

        current_tool_frame = ttk.Frame(overall_frame, padding='0.1i')
        self.current_tool_lbl = ttk.Label(
            current_tool_frame,
            text="Current Tool: {}".format(self.tool_name),
            justify=tk.LEFT)  # , font=("Helvetica", 12, "bold")
        self.current_tool_lbl.grid(row=0, column=0, sticky=tk.W)
        self.view_code_button = ttk.Button(current_tool_frame,
                                           text="View Code",
                                           width=12,
                                           command=self.view_code)
        self.view_code_button.grid(row=0, column=1, sticky=tk.E)
        current_tool_frame.grid(row=1, column=0, sticky=tk.NSEW)
        current_tool_frame.columnconfigure(0, weight=1)
        current_tool_frame.columnconfigure(1, weight=1)

        tool_args_frame = ttk.Frame(overall_frame, padding='0.0i')
        self.tool_args_frame = ttk.Frame(overall_frame, padding='0.0i')
        self.tool_args_frame.grid(row=2, column=0, sticky=tk.NSEW)
        self.tool_args_frame.columnconfigure(0, weight=1)

        # args_frame = ttk.Frame(overall_frame, padding='0.1i')
        # self.args_label = ttk.Label(args_frame, text="Tool Arguments:", justify=tk.LEFT)
        # self.args_label.grid(row=0, column=0, sticky=tk.W)
        # args_frame2 = ttk.Frame(args_frame, padding='0.0i')
        # self.args_value = tk.StringVar()
        # self.args_text = ttk.Entry(args_frame2, width=45, justify=tk.LEFT, textvariable=self.args_value)
        # self.args_text.grid(row=0, column=0, sticky=tk.NSEW)
        # self.args_text.columnconfigure(0, weight=1)
        # self.clearButton = ttk.Button(args_frame2, text="Clear", width=4, command=self.clear_args_box)
        # self.clearButton.pack(pady=10, padx=10)
        # self.clearButton.grid(row=0, column=1, sticky=tk.E)
        # self.clearButton.columnconfigure(0, weight=1)
        # args_frame2.grid(row=1, column=0, sticky=tk.NSEW)
        # args_frame2.columnconfigure(0, weight=10)
        # args_frame2.columnconfigure(1, weight=1)
        # args_frame.grid(row=2, column=0, sticky=tk.NSEW)
        # args_frame.columnconfigure(0, weight=1)

        # # Add the bindings
        # if _platform == "darwin":
        #     self.args_text.bind("<Command-Key-a>", self.args_select_all)
        # else:
        #     self.args_text.bind("<Control-Key-a>", self.args_select_all)

        buttonsFrame = ttk.Frame(overall_frame, padding='0.1i')
        self.run_button = ttk.Button(buttonsFrame,
                                     text="Run",
                                     width=8,
                                     command=self.run_tool)
        # self.run_button.pack(pady=10, padx=10)
        self.run_button.grid(row=0, column=0)
        self.quitButton = ttk.Button(buttonsFrame,
                                     text="Cancel",
                                     width=8,
                                     command=self.cancel_operation)
        self.quitButton.grid(row=0, column=1)
        buttonsFrame.grid(row=3, column=0, sticky=tk.E)

        output_frame = ttk.Frame(overall_frame, padding='0.1i')
        outlabel = ttk.Label(output_frame, text="Output:", justify=tk.LEFT)
        outlabel.grid(row=0, column=0, sticky=tk.NW)
        k = wbt.tool_help(self.tool_name)
        self.out_text = ScrolledText(output_frame,
                                     width=63,
                                     height=10,
                                     wrap=tk.NONE,
                                     padx=7,
                                     pady=7)
        self.out_text.insert(tk.END, k)
        self.out_text.grid(row=1, column=0, sticky=tk.NSEW)
        self.out_text.columnconfigure(0, weight=1)
        output_frame.grid(row=4, column=0, sticky=tk.NSEW)
        output_frame.columnconfigure(0, weight=1)

        # Add the binding
        if _platform == "darwin":
            self.out_text.bind("<Command-Key-a>", self.select_all)
            # self.out_text.bind("<Command-Key-A>", self.select_all)
        else:
            self.out_text.bind("<Control-Key-a>", self.select_all)

        progress_frame = ttk.Frame(overall_frame, padding='0.1i')
        self.progress_label = ttk.Label(progress_frame,
                                        text="Progress:",
                                        justify=tk.LEFT)
        self.progress_label.grid(row=0, column=0, sticky=tk.E, padx=5)
        self.progress_var = tk.DoubleVar()
        self.progress = ttk.Progressbar(progress_frame,
                                        orient="horizontal",
                                        variable=self.progress_var,
                                        length=200,
                                        maximum=100)
        self.progress.grid(row=0, column=1, sticky=tk.E)
        progress_frame.grid(row=5, column=0, sticky=tk.E)

        overall_frame.grid(row=0, column=1, sticky=tk.NSEW)

        overall_frame.columnconfigure(0, weight=1)
        toplevel_frame.columnconfigure(0, weight=1)
        toplevel_frame.columnconfigure(1, weight=4)
        # self.pack(fill=tk.BOTH, expand=1)
        # toplevel_frame.columnconfigure(0, weight=1)
        # toplevel_frame.rowconfigure(0, weight=1)

        toplevel_frame.grid(row=0, column=0, sticky=tk.NSEW)

        # Select the appropriate tool, if specified, otherwise the first tool
        self.tools_listbox.select_set(selected_item)
        self.tools_listbox.event_generate("<<ListboxSelect>>")
        self.tools_listbox.see(selected_item)

        menubar = tk.Menu(self)
        filemenu = tk.Menu(menubar, tearoff=0)
        filemenu.add_command(label="Set Working Directory",
                             command=self.set_directory)
        filemenu.add_command(label="Locate WhiteboxTools exe",
                             command=self.select_exe)
        filemenu.add_command(label="Refresh Tools", command=self.refresh_tools)
        filemenu.add_separator()
        filemenu.add_command(label="Exit", command=self.quit)
        menubar.add_cascade(label="File", menu=filemenu)

        editmenu = tk.Menu(menubar, tearoff=0)
        editmenu.add_command(
            label="Cut",
            command=lambda: self.focus_get().event_generate("<<Cut>>"))
        editmenu.add_command(
            label="Copy",
            command=lambda: self.focus_get().event_generate("<<Copy>>"))
        editmenu.add_command(
            label="Paste",
            command=lambda: self.focus_get().event_generate("<<Paste>>"))

        menubar.add_cascade(label="Edit ", menu=editmenu)

        helpmenu = tk.Menu(menubar, tearoff=0)
        helpmenu.add_command(label="About", command=self.help)

        helpmenu.add_command(label="License", command=self.license)

        menubar.add_cascade(label="Help ", menu=helpmenu)

        self.master.config(menu=menubar)
예제 #27
0
파일: interface.py 프로젝트: edgarJ91/tytus
    def __init__(self,root):
        
        root.title("Grupo 8 Estructuras de Datos")
        root.geometry("600x600")
        barraMenu = tk.Menu(root)
        root.config(menu = barraMenu)
        fileMenu = tk.Menu(barraMenu, tearoff=0)
        fileMenu.add_command(label="Cargar Archivo...", command = self.cargarArchivo)
        fileMenu.add_command(label = "Load", command = self.load)
        fileMenu.add_separator()
        fileMenu.add_command(label = "Salir", command = root.quit) 
        ayuda = tk.Menu(barraMenu, tearoff=0)
        ayuda.add_command(label = "Licencia", command = self.Licencia)
        ayuda.add_separator()
        ayuda.add_command(label = "Acerca de...", command = self.integrantes)
        barraMenu.add_cascade(label="Opciones", menu = fileMenu)
        barraMenu.add_cascade(label="Ayuda", menu = ayuda)

        #MultiPanel
        self.pestanias = ttk.Notebook(root)
        # Agregar Pestañas
        self.basesDatos = ttk.Frame(self.pestanias)
        self.tablas = ttk.Frame(self.pestanias)
        self.tuplas = ttk.Frame(self.pestanias)

        self.pestanias.add(self.basesDatos, text = "Bases de Datos")
        self.pestanias.add(self.tablas, text = "Tablas")
        self.pestanias.add(self.tuplas, text = "Tuplas")

        #-----------------------Contenido Base Datos----------------------------------
        self.lblingresarbase = ttk.Label(self.basesDatos, text = "CreateDatabase")
        self.lblingresarbase.place(x=90,y=100)

        self.txtBase = ttk.Entry(self.basesDatos, width=25)
        self.txtBase.place(x=250, y= 100)

        self.lblSelect = ttk.Label(self.basesDatos, text = "Select DataBase")
        self.lblSelect.place(x=90, y=140)

        self.txtSelect = ttk.Entry(self.basesDatos, width=25)
        self.txtSelect.place(x=250, y=140)

        self.lblupdate = ttk.Label(self.basesDatos, text = "AlterDataBase")
        self.lblupdate.place(x=90, y=180)

        self.txtupdate = ttk.Entry(self.basesDatos, width =25)
        self.txtupdate.place(x=250, y=180)

        self.lbldropDT = ttk.Label(self.basesDatos, text="DropDataBase")
        self.lbldropDT.place(x=90, y=220)

        self.txtdropDT = ttk.Entry(self.basesDatos,width=25)
        self.txtdropDT.place(x=250, y= 220)

        self.txtcheckB = ttk.Entry(self.basesDatos,width=5)
        self.txtcheckB.place(x=230, y= 380)

        #----------------------------------Botones DataBase-----------------------------------------------
        self.btnagg = ttk.Button(self.basesDatos, text = "Crear", command = self.dbcreate)
        self.btnagg.place(x=420, y = 99)

        self.btnupadate = ttk.Button(self.basesDatos, text = "Actualizar", command = self.alterDB)
        self.btnupadate.place(x=420, y=179)

        self.btndrop = ttk.Button(self.basesDatos, text = "Borrar", command = self.dropDB)
        self.btndrop.place(x=420, y=220)

        self.btnmostrarbases = ttk.Button(self.basesDatos, text = "ShowDataBase", command=self.muestraDataBaseG)
        self.btnmostrarbases.place(x = 250 , y = 280, width = 150, height = 30)

        self.btnmostrarbases = ttk.Button(self.basesDatos, text = "Guardar", command=self.guardarBases)
        self.btnmostrarbases.place(x = 275 , y = 330, width = 100, height = 30)

        self.btnmostrarbases = ttk.Button(self.basesDatos, text = "Graphviz", command=self.generarGrapBases)
        self.btnmostrarbases.place(x = 275 , y = 380, width = 100, height = 30)

        # ------------------------Contenido Pestaña Tablas-------------------------------------

        self.lblselecionbase = ttk.Label(self.tablas, text = "Seleccionar DB")
        self.lblselecionbase.place(x=90,y=30)

        self.txtBaseSelec = ttk.Entry(self.tablas, width=25)
        self.txtBaseSelec.place(x=250, y= 30)

        self.lbltable = ttk.Label(self.tablas, text = "Table")
        self.lbltable.place(x=90, y=70)

        self.txttable = ttk.Entry(self.tablas, width =25)
        self.txttable.place(x=250, y=70)

        self.lblnumcol = ttk.Label(self.tablas, text="NumberColumns")
        self.lblnumcol.place(x=90, y=110)

        self.txtnumcol = ttk.Entry(self.tablas,width=25)
        self.txtnumcol.place(x=250, y= 110)

        self.lblcolums = ttk.Label(self.tablas, text = "Columns")
        self.lblcolums.place(x=90, y = 150)

        self.txtcolums = ttk.Entry(self.tablas, width = 25)
        self.txtcolums.place(x=250, y = 150)

        self.lbllow = ttk.Label(self.tablas, text = "Low")
        self.lbllow.place(x=90, y=190)

        self.txtlow = ttk.Entry(self.tablas, width = 25)
        self.txtlow.place(x=250, y = 190)

        self.lblupper = ttk.Label(self.tablas, text = "Upper")
        self.lblupper.place(x=90, y = 230)

        self.txtupper = ttk.Entry(self.tablas, width = 25)
        self.txtupper.place(x=250,y=230)

        self.lblreference = ttk.Label(self.tablas, text = "References",)
        self.lblreference.place(x=90, y= 270)

        self.txtreference = ttk.Entry(self.tablas, width = 25)
        self.txtreference.place(x=250, y = 270)

        self.lbltablenew = ttk.Label(self.tablas, text = "TableNew")
        self.lbltablenew.place(x=90, y= 310)

        self.txttablenew = ttk.Entry(self.tablas, width = 25)
        self.txttablenew.place(x=250, y = 310)

        self.lbldefault = ttk.Label(self.tablas, text = "Default")
        self.lbldefault.place(x= 90, y = 350)

        self.txtdefault = ttk.Entry(self.tablas, width=25)
        self.txtdefault.place(x=250,y = 350)

        self.txtguardarTabla = ttk.Entry(self.tablas, width=5)
        self.txtguardarTabla.place(x=170,y = 510)

        #-------------------------Botones Tablas-------------------------------------------
        self.btnaggtable = ttk.Button(self.tablas, text = "Create",command=self.dbCreateTable)
        self.btnaggtable.place(x=90, y = 400)

        self.btndrop = ttk.Button(self.tablas, text = "AlterTable", command = self.alterTable)
        self.btndrop.place(x=210, y=400)

        self.btndroptable = ttk.Button(self.tablas, text = "Drop", command = self.dropTable)
        self.btndroptable.place(x=330, y= 400)

        self.btnalterPK = ttk.Button(self.tablas, text = "AlterPK", command = self.alterAddPKT)
        self.btnalterPK.place(x=450, y=400)

        self.btnalterdropPk = ttk.Button(self.tablas, text = "AlterDropPK", command = self.alterDropPKT)
        self.btnalterdropPk.place(x=90,y=450)

        self.btnalterColumn = ttk.Button(self.tablas, text = "AlterAddColumn", command = self.alterAddColumn)
        self.btnalterColumn.place(x= 210, y=450)
        
        self.btnalterColumn = ttk.Button(self.tablas, text = "Guardar", command = self.guardarTablas)
        self.btnalterColumn.place(x= 210, y=510)

        self.btnalterColumn = ttk.Button(self.tablas, text = "Graphviz", command = self.generarGrapTablas)
        self.btnalterColumn.place(x= 330, y=510)

        self.btnalterDropColum = ttk.Button(self.tablas, text = "AlterDropColumn", command = self.alterAddColumn)
        self.btnalterDropColum.place(x=330,y=450)

        self.btnrangetable = ttk.Button(self.tablas, text= "ExtractRangeTable", command = self.extractRangeT)
        self.btnrangetable.place(x=450, y= 450)

        self.btnextracttable = ttk.Button(self.tablas, text = "Extract Table", command = self.extractTb)
        self.btnextracttable.place(x= 420, y= 70)

        self.btnmostrartablas = ttk.Button(self.tablas, text = "ShowTables", command=self.muestraTablas)
        self.btnmostrartablas.place(x = 420 , y = 30)

        #-----------------------------Contenido Pestaña Tuplas-------------------------------------
        self.txtcheckTPL = ttk.Entry(self.tuplas, width = 5)
        self.txtcheckTPL.place(x=80, y = 430)
        
        self.lblselectDatabase = ttk.Label(self.tuplas, text = "Select Database")
        self.lblselectDatabase.place(x = 110, y = 50)

        self.txtselectDatabase = ttk.Entry(self.tuplas, width = 25 )
        self.txtselectDatabase.place(x=270, y = 50)

        self.lblselectTablet = ttk.Label(self.tuplas, text = "Select Table")
        self.lblselectTablet.place(x=110, y = 90)

        self.txtselectTablet = ttk.Entry(self.tuplas, width = 25)
        self.txtselectTablet.place(x=270, y = 90)

        self.lblselectcolumn = ttk.Label(self.tuplas, text= "Select Columns")
        self.lblselectcolumn.place(x=110, y = 130)

        self.txtinsert = ttk.Entry(self.tuplas, width = 25)
        self.txtinsert.place(x = 270, y = 130)

        self.lblregister = ttk.Label(self.tuplas, text = "Select Register")
        self.lblregister.place(x=110, y = 170)

        self.txtregister = ttk.Entry(self.tuplas, width = 25)
        self.txtregister.place(x= 270, y = 170)

        self.lblfile = ttk.Label(self.tuplas, text = "File")
        self.lblfile.place(x=110, y = 210)

        self.txtfile = ttk.Entry(self.tuplas, width = 25)
        self.txtfile.place(x=270, y = 210)


        #------------------------------------Botones Tuplas--------------------------------------------------
        self.btninsert = ttk.Button(self.tuplas, text = "Insert", command = self.insertTupla)
        self.btninsert.place(x=120, y = 290,width = 130, height = 30)

        self.btnload = ttk.Button(self.tuplas, text = "LoadCSV", command = self.cargarArchivo)
        self.btnload.place(x=300, y = 290,width = 130, height = 30)

        self.btnextractRow = ttk.Button(self.tuplas, text = "ExtractRow", command = self.motrarRow)
        self.btnextractRow.place(x=120, y= 340,width = 130, height = 30)

        self.btnupdatetupla = ttk.Button(self.tuplas, text = "Update")
        self.btnupdatetupla.place(x=300, y= 340, width = 130, height = 30)

        self.btndelate = ttk.Button(self.tuplas, text = "Delete")
        self.btndelate.place (x=120, y = 380, width = 130, height = 30)

        self.btntruncate = ttk.Button(self.tuplas, text = "Truncate")
        self.btntruncate.place(x=300, y= 380, width = 130, height = 30)

        self.btngraphviz = ttk.Button(self.tuplas, text = "Graphviz", command = self.generarGrapTuplas)
        self.btngraphviz.place(x=120, y = 430, width = 130, height = 30)
        
        self.btngraphviz = ttk.Button(self.tuplas, text = "Guardar", command = self.guardarTuplas)
        self.btngraphviz.place(x=300, y = 430, width = 130, height = 30)

        self.pestanias.pack(expand = 1, fill = "both")
예제 #28
0
    def __init__(self, master, width, camera_index=0, max_fps=20):
        self.master = master
        self.width = width

        # Define render constants
        self.image_render_size = width // 4 # all variables are defined in terms of width, including the height
        self.padding = width // 128
        self.font_size = width // 64
        self.box_height = 2*self.padding + self.font_size
        self.box_width = width - 3*self.padding - self.image_render_size
        self.instructions_top = max(10*self.box_height, 11*self.padding, self.image_render_size + 5*self.font_size + 9*self.padding) # the max function is used to be safe, as it is unclear which column of the app is lower, and this may vary with height
        self.height = self.instructions_top + 10*self.font_size + 12*self.padding

        # Update Master
        master.resizable(False, False)
        master.geometry(f"{width}x{self.height}")
        master.update()

        # Set up camera
        self.capture = cv2.VideoCapture(camera_index)
        self.max_fps = max_fps

        """
            Annoyingly, the camera resolution can only be set to a few options, so setting the width followed by
            getting the width will often return different values. Thus, when the width is 'set', values like 1 can
            be entered without risk of the camera resolution dropping to 1x1; it will simply pick the lowest
            possible resolution. This code was written on a laptop with a default resolution of 640x480.
        """
        self.capture.set(cv2.CAP_PROP_FRAME_WIDTH, 1)
        self.cap_width = int(self.capture.get(cv2.CAP_PROP_FRAME_WIDTH))
        self.cap_height = int(self.capture.get(cv2.CAP_PROP_FRAME_HEIGHT))

        # Misc variables
        self.started = False
        self.cutoff = 40

        # Trainer
        self.trainer = Trainer(DATA_ITERATORS[0], True)

        # Layout (first, since menus use layout variables)
        self.main_canvas = tk.Canvas(master, width=width, height=self.height)
        self.main_canvas.configure(background="#FFFF80")
        self.main_canvas.pack(fill="both")

        # Menus
        self.menu_main = tk.Menu(master, tearoff=0)
        master.config(menu=self.menu_main)

        self.menu_mode = tk.Menu(self.menu_main, tearoff=0)
        self.menu_main.add_cascade(label="Mode", menu=self.menu_mode)
        self.mode = tk.IntVar()
        for value, label in enumerate(("Training", "Video", "Drawing")):
            self.menu_mode.add_radiobutton(label=label+" Mode", variable=self.mode, value=value, command=self.update)

        self.menu_dataset = tk.Menu(self.menu_main, tearoff=0)
        self.menu_main.add_cascade(label="Dataset", menu=self.menu_dataset)
        self.dataset = tk.IntVar()
        for value, label in enumerate(("Digits", "Fashion", "CIFAR-10")):
            self.menu_dataset.add_radiobutton(label=label, variable=self.dataset, value=value, command=self.update)

        self.menu_step = tk.Menu(self.menu_main, tearoff=0)
        self.menu_main.add_cascade(label="Step", menu=self.menu_step)
        self.menu_step.add_command(label="Single", command=self.training_step)

        self.update()
예제 #29
0
    def _initSelect(self):
        self._duplicates = Setting.Data.duplicates

        self._items = Data._dict

        oframe = tkinter.LabelFrame(self, text='Selection')
        oframe.pack()

        self.bind('<Left>', self.reset)
        self.bind('<Up>', self.difference)
        self.bind('<Down>', self.delete)
        self.bind('<Right>', self.next)
        self.bind('<space>', self.toggle)

        frame = tkinter.Frame(oframe)
        frame.pack(expand=True, fill=tkinter.X)

        self._nextButton = tkinter.Button(frame, text='Next (Right)')
        self._nextButton._command = self._nextButton['command'] = self.next
        self._nextButton.pack(expand=True, fill=tkinter.X, side=tkinter.LEFT)

        tkinter.Button(frame, text='Difference (Up)',
                       command=self.difference).pack(expand=True,
                                                     fill=tkinter.X,
                                                     side=tkinter.LEFT)

        self._deleteButton = tkinter.Button(frame,
                                            text='Delete (Down)',
                                            command=self.delete)
        self._deleteButton._command = self._deleteButton[
            'command'] = self.delete
        self._deleteButton.pack(expand=True, fill=tkinter.X, side=tkinter.LEFT)

        tkinter.Button(frame, text='Uncheck All',
                       command=self.uncheck).pack(expand=True,
                                                  fill=tkinter.X,
                                                  side=tkinter.LEFT)

        self._vButtonsFrame = tkinter.Frame(oframe)
        self._vButtonsFrame.pack(expand=True, fill=tkinter.X)

        tkinter.Button(self._vButtonsFrame,
                       text='Start (Space)',
                       command=self.start).pack(expand=True,
                                                fill=tkinter.X,
                                                side=tkinter.LEFT)
        tkinter.Button(self._vButtonsFrame,
                       text='Stop (Space)',
                       command=self.stop).pack(expand=True,
                                               fill=tkinter.X,
                                               side=tkinter.LEFT)
        tkinter.Button(self._vButtonsFrame,
                       text='Reset (Left)',
                       command=self.reset).pack(expand=True,
                                                fill=tkinter.X,
                                                side=tkinter.LEFT)

        self._menu = tkinter.Menu(self, tearoff=0)
        self._menu.add_command(label='Start',
                               command=lambda: self._menu._mframe.play())
        self._menu.add_command(label='Stop',
                               command=lambda: self._menu._mframe.stop())
        self._menu.add_command(label='Reset',
                               command=lambda: self._menu._mframe.reset())

        keyFrame = tkinter.LabelFrame(oframe)
        keyFrame.pack()

        self._frame = tkinter.Frame(keyFrame)

        self.skip()
예제 #30
0
    def interface(self):
        self.client = Client(self.host1, self.port1, self.user)
        self.receive = self.client.start()
        root = tk.Tk()
        root.title('Chatroom')
        root.rowconfigure(0, minsize=500, weight=1)
        root.rowconfigure(1, minsize=50, weight=0)
        root.columnconfigure(0, minsize=500, weight=1)
        root.columnconfigure(1, minsize=200, weight=0)

        # menu

        menubar = tk.Menu(root)
        file = tk.Menu(menubar, tearoff=0)
        # file.add_command(label="New")
        # file.add_command(label="Open")
        # file.add_command(label="Save")
        # file.add_command(label="Save as...")
        # file.add_command(label="Close")

        file.add_separator()

        file.add_command(label="Exit",
                         command=lambda: self.client.send('QUIT'))

        menubar.add_cascade(label="File", menu=file)
        edit = tk.Menu(menubar, tearoff=0)
        # edit.add_command(label="Undo")

        edit.add_separator()

        # edit.add_command(label="Cut")
        # edit.add_command(label="Copy")
        # edit.add_command(label="Paste")
        edit.add_command(label="Delete",
                         command=lambda: self.del_db(frm_messages))
        # edit.add_command(label="Select All")

        menubar.add_cascade(label="Edit", menu=edit)
        help = tk.Menu(menubar, tearoff=0)
        help.add_command(label="About", command=lambda: self.about())
        menubar.add_cascade(label="Help", menu=help)

        root.config(menu=menubar)

        frm_messages = tk.Frame(master=root)
        scrollbar = tk.Scrollbar(master=frm_messages)
        messages = tk.Listbox(master=frm_messages,
                              yscrollcommand=scrollbar.set)

        scrollbar.pack(side=tk.RIGHT, fill=tk.Y, expand=False)
        messages.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        #
        self.client.messages = messages
        self.receive.messages = messages

        frm_messages.grid(row=0, column=0, columnspan=2, sticky="nsew")

        frm_entry = tk.Frame(master=root)
        text_input = tk.Entry(master=frm_entry)
        text_input.pack(fill=tk.BOTH, expand=True)
        self.client.load_old_message()
        text_input.bind("<Return>", lambda x: self.client.send(text_input))
        text_input.insert(0, "Your message here.")

        btn_send = tk.Button(master=root,
                             text='Send',
                             command=lambda: self.root.destroy())
        btn_send["command"] = lambda: self.command_btn_send(text_input)
        frm_entry.grid(row=1, column=0, padx=10, sticky="ew")
        btn_send.grid(row=1, column=1, pady=10, sticky="ew")
        root.mainloop()