Exemplo n.º 1
0
class XLABaseTest(unittest.TestCase):
    """Provides the model and config of PolI"""
    def setUp(self, mPaths, cPath):
        mPath = xlinkanalyzer.__path__[0]
        xlaTestPath = path.join(path.split(mPath)[0], 'pytests/test_data')
        self.xlaTestMPaths = [
            path.join(xlaTestPath, _path) for _path in mPaths
        ]
        self.xlaTestCPath = path.join(xlaTestPath, cPath)

        self.config = Assembly()
        self.rManager = ResourceManager(self.config)
        self.rManager.loadAssembly(None, self.xlaTestCPath)

        [chimera.openModels.open(_path) for _path in self.xlaTestMPaths]
        self.models = chimera.openModels.list()
        # self.xla_models = [Model(chimeraModel, self.config) for chimeraModel in self.models]

    def _createTestWindow(self):
        self.testWindow = Toplevel()
        w = self.testWindow.winfo_screenwidth()
        h = self.testWindow.winfo_screenheight()
        x = w / 2
        y = h / 2
        self.testWindow.geometry("+%d+%d" % (x, y))
        self.testWindow.geometry("400x200")

    def tearDown(self):
        chimera.openModels.close(chimera.openModels.list())
Exemplo n.º 2
0
class XLABaseTest(unittest.TestCase):
    """Provides the model and config of PolI"""

    def setUp(self, mPaths, cPath):
        mPath = xlinkanalyzer.__path__[0]
        xlaTestPath = path.join(path.split(mPath)[0], 'pytests/test_data')
        self.xlaTestMPaths = [path.join(xlaTestPath, _path) for _path in mPaths]
        self.xlaTestCPath = path.join(xlaTestPath, cPath)

        self.config = Assembly()
        self.rManager = ResourceManager(self.config)
        self.rManager.loadAssembly(None, self.xlaTestCPath)

        [chimera.openModels.open(_path) for _path in self.xlaTestMPaths]
        self.models = chimera.openModels.list()
        # self.xla_models = [Model(chimeraModel, self.config) for chimeraModel in self.models]

    def _createTestWindow(self):
        self.testWindow = Toplevel()
        w = self.testWindow.winfo_screenwidth()
        h = self.testWindow.winfo_screenheight()
        x = w/2
        y = h/2
        self.testWindow.geometry("+%d+%d" % (x, y))
        self.testWindow.geometry("400x200")

    def tearDown(self):
        chimera.openModels.close(chimera.openModels.list())
Exemplo n.º 3
0
def _calltip_window(parent):  # htest #
    from Tkinter import Toplevel, Text, LEFT, BOTH

    top = Toplevel(parent)
    top.title("Test calltips")
    top.geometry("200x100+%d+%d" %
                 (parent.winfo_rootx() + 200, parent.winfo_rooty() + 150))
    text = Text(top)
    text.pack(side=LEFT, fill=BOTH, expand=1)
    text.insert("insert", "string.split")
    top.update()
    calltip = CallTip(text)

    def calltip_show(event):
        calltip.showtip("(s=Hello world)", "insert", "end")

    def calltip_hide(event):
        calltip.hidetip()

    text.event_add("<<calltip-show>>", "(")
    text.event_add("<<calltip-hide>>", ")")
    # - 2016 9 28 --
    text.event_add('<<calltip-show>>', '<less>')
    text.event_add('<<calltip-hide>>', '<greater>')
    # ---
    text.bind("<<calltip-show>>", calltip_show)
    text.bind("<<calltip-hide>>", calltip_hide)
    text.focus_set()
Exemplo n.º 4
0
def _io_binding(parent):  # htest #
    root = Toplevel(parent)
    root.title("Test IOBinding")
    width, height, x, y = list(map(int, re.split('[x+]', parent.geometry())))
    root.geometry("+%d+%d"%(x, y + 150))
    class MyEditWin:
        def __init__(self, text):
            self.text = text
            self.flist = None
            self.text.bind("<Control-o>", self.open)
            self.text.bind("<Control-s>", self.save)
        def get_saved(self): return 0
        def set_saved(self, flag): pass
        def reset_undo(self): pass
        def open(self, event):
            self.text.event_generate("<<open-window-from-file>>")
        def save(self, event):
            self.text.event_generate("<<save-window>>")
        def update_recent_files_list(s, f): pass

    text = Text(root)
    text.pack()
    text.focus_set()
    editwin = MyEditWin(text)
    IOBinding(editwin)
Exemplo n.º 5
0
def documentation(version, w, h):
    def _setdoc(evt):
        w = evt.widget
        index = int(w.curselection()[0])
        doc = w.get(index)
        textfield.config(state=NORMAL)
        textfield.delete('1.0', END)
        textfield.insert('1.0', docdic[doc])
        textfield.config(state=DISABLED)
    r = Toplevel()
    w = int(w/2)
    h = int(h/2)
    r.geometry('{}x{}+{}+{}'.format(w, h, int(w/2), int(h/2)))
    r.wm_title('Documentation accpy version {}'.format(version))

    lf = Frame(r)
    lf.pack(side=LEFT, fill=BOTH, expand=False)
    rf = Frame(r)
    rf.pack(side=RIGHT, fill=BOTH, expand=True)

    docmenuopts = ['General',
                   'Lattice editor',
                   'Citation']
    docmenu = Listbox(lf)
    for entry in docmenuopts:
        docmenu.insert(END, entry)
    docmenu.pack(fill=BOTH, expand=True)
    docmenu.bind('<<ListboxSelect>>', _setdoc)

    scrollbar = Scrollbar(orient="vertical")
    textfield = Text(rf, xscrollcommand=scrollbar.set)
    textfield.pack(fill=BOTH, expand=True)
Exemplo n.º 6
0
def save(squares):
    """
    Handle the save key on the main window.
    """
    def save_button_hit():
        """
        Save key (on local window) was hit.  Save the file name entered.
        """
        text_in = save_entry.get().strip()
        if len(text_in) == 0:
            showwarning('Error', 'File name specified is empty.')
            return
        outfile = os.path.join(savedir, text_in)
        with open(outfile, 'w') as fyle:
            for sqr_info in save_squares:
                fyle.write('%d:%d:%s\n' % tuple(save_squares[sqr_info]))
        top.destroy()
    top = Toplevel()
    top.geometry('180x80+800+200')
    top.title('Save a layout')
    save_squares = squares
    savedir = getdir()
    label1 = Label(top, text='File name')
    save_entry = Entry(top)
    label1.grid(row=0)
    save_entry.grid(row=0, column=1, columnspan=2)
    save_entry.focus_set()
    save_button = Button(top, text='SAVE', pady=3,
            command=save_button_hit)
    sspace = Label(top)
    sspace.grid(row=1)
    save_button.grid(row=2, column=1)
    top.mainloop()
Exemplo n.º 7
0
def _io_binding(parent):  # htest #
    from Tkinter import Toplevel, Text
    from idlelib.configHandler import idleConf

    root = Toplevel(parent)
    root.title("Test IOBinding")
    width, height, x, y = list(map(int, re.split('[x+]', parent.geometry())))
    root.geometry("+%d+%d"%(x, y + 150))
    class MyEditWin:
        def __init__(self, text):
            self.text = text
            self.flist = None
            self.text.bind("<Control-o>", self.open)
            self.text.bind("<Control-s>", self.save)
        def get_saved(self): return 0
        def set_saved(self, flag): pass
        def reset_undo(self): pass
        def open(self, event):
            self.text.event_generate("<<open-window-from-file>>")
        def save(self, event):
            self.text.event_generate("<<save-window>>")
        def update_recent_files_list(s, f): pass

    text = Text(root)
    text.pack()
    text.focus_set()
    editwin = MyEditWin(text)
    IOBinding(editwin)
Exemplo n.º 8
0
    def instructions(self):
        """Open instructions window."""
        # Instantiates separate Toplevel instruction window.
        instr_window = Toplevel(self.root)
        instr_window.geometry('550x575+25+25')
        instr_window.title('Instructions')
        instr_window.wm_iconbitmap(constants.ICO)
        instr_window.resizable(False, False)

        # Creatse Scrollbar and Frame for containing other widgets.
        instr_scroll = Scrollbar(instr_window)
        instr_scroll.pack(fill=Y, side="right")
        instr_frame = Frame(instr_window, bg='white')
        instr_frame.pack(fill=BOTH, side="left")

        # Adds instruction text from constants and adds image of Cinzano's diagram.
        instr = Text(instr_frame,
                     width=65,
                     height=40,
                     padx=10,
                     pady=5,
                     bd=0,
                     wrap="word")
        instr.insert("end", constants.INSTR)
        cdiagram_file = Image.open("./static/cinzano_diagram.PNG")
        cdiagram_file = cdiagram_file.resize((500, 450), Image.ANTIALIAS)
        self.cdiag = ImageTk.PhotoImage(cdiagram_file)
        instr.image_create("end", image=self.cdiag)
        instr.tag_add("top", "1.0", "4.10")
        instr.tag_config("top", font='Times 12 bold')
        instr.tag_add("body", "5.0", "19.20")
        instr.tag_config("body", font='Times 12')
        instr.insert("end", constants.CDIAG)
        instr.pack()
        instr_scroll.config(command=instr.yview)
Exemplo n.º 9
0
def _calltip_window(parent):  # htest #
    from Tkinter import Toplevel, Text, LEFT, BOTH

    top = Toplevel(parent)
    top.title("Test calltips")
    top.geometry("200x100+%d+%d" % (parent.winfo_rootx() + 200,
                  parent.winfo_rooty() + 150))
    text = Text(top)
    text.pack(side=LEFT, fill=BOTH, expand=1)
    text.insert("insert", "string.split")
    top.update()
    calltip = CallTip(text)

    def calltip_show(event):
        calltip.showtip("(s=Hello world)", "insert", "end")
    def calltip_hide(event):
        calltip.hidetip()
    text.event_add("<<calltip-show>>", "(")
    text.event_add("<<calltip-hide>>", ")")
    # - 2016 9 28 --
    text.event_add('<<calltip-show>>', '<less>')
    text.event_add('<<calltip-hide>>', '<greater>')
    # ---
    text.bind("<<calltip-show>>", calltip_show)
    text.bind("<<calltip-hide>>", calltip_hide)
    text.focus_set()
Exemplo n.º 10
0
    def set_file(self):
        window = Toplevel(self, bg='#C1CDCD')
        window.title('set_file_size')
        window.geometry('400x400')
        window.resizable(0, 0)  # 禁止调整窗口大小

        file_num = 16
        var = []
        for i in range(file_num):
            var.append(StringVar())
        Label(window, text=u"请填写需要生成的测试文件大小,单位M(无需填满):",
              bg='#C1CDCD').grid(row=0,
                                 column=0,
                                 columnspan=4,
                                 pady=5,
                                 padx=15)
        for j in range(file_num / 2):
            Label(window, text=u"文件大小" + str(j * 2) + ":",
                  bg='#C1CDCD').grid(row=j + 1, column=0, pady=8, padx=10)
            Entry(window, width=10, textvariable=var[j * 2]).grid(row=j + 1,
                                                                  column=1,
                                                                  pady=8,
                                                                  padx=10)
            Label(window, text=u"文件大小" + str(j * 2 + 1) + ":",
                  bg='#C1CDCD').grid(row=j + 1, column=2, pady=8, padx=10)
            Entry(window, width=10,
                  textvariable=var[j * 2 + 1]).grid(row=j + 1,
                                                    column=3,
                                                    pady=8,
                                                    padx=10)

        def get_file_list():
            v3 = ''
            self.file_list[:] = []
            for k in range(file_num):
                v = var[k].get()
                if v == '' or v.isspace() or not v.isdigit():
                    continue
                else:
                    self.file_list.append(int(v))
            self.file_list = list(set(self.file_list))
            if 0 in self.file_list:
                self.file_list.remove(0)
            self.file_list.sort()
            for size in self.file_list:
                v3 = v3 + str(size) + 'M' + ','
            print v3
            self.v3.set(v3)
            window.destroy()

        Button(window,
               text=u"确定",
               width=20,
               command=get_file_list,
               bg='#C1CDCD').grid(row=file_num / 2 + 2,
                                  column=0,
                                  columnspan=4,
                                  pady=8,
                                  padx=10)
        window.protocol("WM_DELETE_WINDOW", window.destroy)
Exemplo n.º 11
0
class Reminder_Window():



    def start_window(self):
        self.reminder_window = Toplevel()
        self.reminder_window.grab_set()
        self.reminder_window.title('Reminder')
        self.reminder_window.geometry('400x200')
        big_font = tkFont.Font(size=10)
        self.reminder_text_1 = Tkinter.Label(self.reminder_window,
        text='Remind me', font=big_font)
        self.reminder_text_2 = Tkinter.Label(self.reminder_window, \
        text='day(s) before.', font=big_font)
        self.reminder_entry = Tkinter.Entry(self.reminder_window, width=3)
        self.ok_reminder_button = Tkinter.Button(self.reminder_window,
        text='OK', command=self.on_ok_button_press)
        self.back_reminder_button = Tkinter.Button(self.reminder_window, \
        text='Back', command=self.on_back_button_press)


        self.reminder_text_1.place(x=x_reminder_text_1_location, \
        y=y_reminder_texts_location)
        self.reminder_text_2.place(x=x_reminder_text_2_location, \
        y=y_reminder_texts_location)
        self.reminder_entry.place(x=x_reminder_entry_location, \
        y=y_reminder_entry_location)
        self.ok_reminder_button.place(x=x_ok_reminder_button_location, \
        y=y_ok_back_reminder_button_locations)
        self.back_reminder_button.place(x=x_back_reminder_button_location, \
        y=y_ok_back_reminder_button_locations)
        self.reminder_window.mainloop()

    def on_ok_button_press(self):
        entry_reminder_value = self.reminder_entry.get()
        try:
            int_entry_reminder_value = int(entry_reminder_value)
            #print 0 > int_entry_reminder_value, int_entry_reminder_value < 50
            if 0 > int_entry_reminder_value or int_entry_reminder_value > 50:
                print 'hi'
                tkMessageBox.showinfo("Error", \
                'Invalid Entry.  Please enter a number from 0-50')
                self.reminder_window.grab_set()
                self.reminder_window.lift()

            else:
                self.num_of_days_before_to_remind_int = int_entry_reminder_value
                self.reminder_window.destroy()

        except ValueError:
            tkMessageBox.showinfo("Error", \
            'Invalid Entry.  Please enter a number from 0-50')
            self.reminder_window.grab_set()
            self.reminder_window.lift()


    def on_back_button_press(self):
        self.num_of_days_before_to_remind_int = 0
        self.reminder_window.destroy()
Exemplo n.º 12
0
 def display_error(self, text_message):
     top = Toplevel()
     x = self.master.winfo_rootx()
     y = self.master.winfo_rooty()
     top.geometry("+%d+%d" %(x+250,y+150))
     #top.geometry("+550+350")
     top.title('Error')
     Tkinter.Label(top, text=text_message).grid(row=1, sticky='W')
     Tkinter.Button(top, text="OK", command=top.destroy).grid(row=2)
Exemplo n.º 13
0
class SplashScreen:

    root = None
    win = None
    img = 'images/splash-screen'
    flag = 0

    def __init__(self, root):
        self.root = root
        self.width = 500
        self.height = 300
        self.flag = config.preferences.show_splash

    def show(self):
        self.root.withdraw()
        if self.flag:
            img_file = os.path.join(app.config.sk_share_dir, self.img + '.png')
            from sk1sdk.tkpng import load_icon
            load_icon(self.root, img_file, self.img)

            scrnWt = self.root.winfo_screenwidth()
            scrnHt = self.root.winfo_screenheight()
            winXPos = (scrnWt / 2) - (self.width / 2)
            winYPos = (scrnHt / 2) - (self.height / 2)

            self.win = Toplevel()
            self.win.overrideredirect(1)
            self.win.configure(background='black')
            self.banner = Label(self.win,
                                image=self.img,
                                cursor='watch',
                                borderwidth=0)
            self.banner.pack()

            self.verlb = Label(self.win,
                               text='version %s' % (config.version, ),
                               bg='white')
            self.verlb.place(x=10, y=240)
            self.verlb['font'] += ' bold'

            self.txtlb = Label(self.win, text='Start...', bg='white')
            self.txtlb.place(x=10, y=265)
            self.progress_bar = SS_ProgressBar(self.win)
            self.progress_bar.pack(fill=X, side=TOP)
            geom = (self.width, self.height, winXPos, winYPos)
            self.win.geometry('%dx%d+%d+%d' % geom)
            self.win.update()

    def hide(self):
        if self.flag and self.win:
            self.win.withdraw()
            self.win.destroy()

    def set_val(self, val, txt=''):
        self.progress_bar.set_val(val)
        if txt: self.txtlb['text'] = txt
        self.win.update()
Exemplo n.º 14
0
class ServerInfoWindow:
    combined_commands = [
        "uptime",
        "users",
        "uname -a",
        "w",
        "who",
        "df -h",
        "cat /etc/hosts",
        "free -h",
        "iostat",
        "vmstat",
    ]

    command_list = [
        "last",
        "ps aux",
        "vmstat -stats",
        "netstat -l",
        "netstat -t",
        "netstat -u",
        "netstat -x",
        "lscpu",
        "ls ~",
    ]

    def __init__(self, name, ssh_connection=None):
        self.name = name
        self.ssh = ssh_connection
        self.window = Toplevel()
        self.window.geometry("800x600")
        self.window.title(name)
        self.window.option_add("*Font", "TkFixedFont")

        self.command_notebook = ttk.Notebook(self.window)
        self.pack_all_command_tabs()
        self.command_notebook.pack(fill=BOTH, expand=1)

    def bring_to_front(self):
        self.window.focus_force()

    def pack_all_command_tabs(self):
        # Combined commands in one tab
        combined_commands_txt = Text(self.command_notebook)
        combined_commands_txt.tag_config("highlight", foreground="blue")
        for command in self.combined_commands:
            stdin, stdout, stderr = self.ssh.exec_command(command)
            combined_commands_txt.insert(END, ("===== " + command + " =====\n").encode("utf-8"), ("highlight",))
            combined_commands_txt.insert(END, stdout.read())
        self.command_notebook.add(combined_commands_txt, text="Info")

        # Individual commands that get their own tab
        for command in self.command_list:
            stdin, stdout, stderr = self.ssh.exec_command(command)
            command_txt = Text(self.command_notebook)
            command_txt.insert(END, stdout.read())
            self.command_notebook.add(command_txt, text=command)
Exemplo n.º 15
0
class SplashScreen:

	root = None
	win = None
	img = 'images/splash-screen'
	flag = 0

	def __init__(self, root):
		self.root = root
		self.width = 500
		self.height = 300
		self.flag = config.preferences.show_splash

	def show(self):
		self.root.withdraw()
		if self.flag:
			img_file = os.path.join(app.config.sk_share_dir, self.img + '.png')
			from sk1sdk.tkpng import load_icon
			load_icon(self.root, img_file, self.img)

			scrnWt = self.root.winfo_screenwidth()
			scrnHt = self.root.winfo_screenheight()
			winXPos = (scrnWt / 2) - (self.width / 2)
			winYPos = (scrnHt / 2) - (self.height / 2)

			self.win = Toplevel()
			self.win.overrideredirect(1)
			self.win.configure(background='black')
			self.banner = Label(self.win, image=self.img, cursor='watch',
							borderwidth=0)
			self.banner.pack()

			self.verlb = Label(self.win, text='version %s' % (config.version,),
							bg='white')
			self.verlb.place(x=10, y=240)
			self.verlb['font'] += ' bold'

			self.txtlb = Label(self.win, text='Start...',
							bg='white')
			self.txtlb.place(x=10, y=265)
			self.progress_bar = SS_ProgressBar(self.win)
			self.progress_bar.pack(fill=X, side=TOP)
			geom = (self.width, self.height, winXPos, winYPos)
			self.win.geometry('%dx%d+%d+%d' % geom)
			self.win.update()

	def hide(self):
		if self.flag and self.win:
			self.win.withdraw()
			self.win.destroy()

	def set_val(self, val, txt=''):
		self.progress_bar.set_val(val)
		if txt: self.txtlb['text'] = txt
		self.win.update()
Exemplo n.º 16
0
def gameOver(points, game):
    toplevel = Toplevel(game, width=200)
    toplevel.geometry("%dx%d%+d%+d" % (200, 200, 200, 200))
    label1 = Label(toplevel, text='Game Over', font=("Helvetica", 14, "bold"), height=0, width=100)
    label1.pack()
    label2 = Label(toplevel, text='Highest tile ' + str(points), font=("Helvetica", 12), height=0, width=100)
    label2.pack()
    btn_end = Button(toplevel, text="End Game", command=partial(game.parent.openMenuFrame, game))
    btn_end.pack()
    btn_new = Button(toplevel, text="New Game", command=partial(game.parent.openGameFrame))
    btn_new.pack()
Exemplo n.º 17
0
class HelpWindow(object):
    def __init__(self,master, title):
        self.top=Toplevel(master)
        self.value = ''
        self.top.geometry("300x300+300+300")
        self.l=Label(self.top,text=title)
        self.l.pack()
        self.b=Button(self.top,text='Ok',command=self.cleanup)
        self.b.pack()
        self.b.focus()
    def cleanup(self):
        self.top.destroy()
Exemplo n.º 18
0
class ServerInfoWindow:
    combined_commands = [
        'uptime',
        'users',
        'uname -a',
        'w',
        'who',
        'df -h',
        'cat /etc/hosts',
        'free -h',
        'iostat',
        'vmstat',
    ]

    command_list = [
        'last', 'ps aux', 'vmstat -stats', 'netstat -l', 'netstat -t',
        'netstat -u', 'netstat -x', 'lscpu', 'ls ~'
    ]

    def __init__(self, name, ssh_connection=None):
        self.name = name
        self.ssh = ssh_connection
        self.window = Toplevel()
        self.window.geometry('800x600')
        self.window.title(name)
        self.window.option_add("*Font", "TkFixedFont")

        self.command_notebook = ttk.Notebook(self.window)
        self.pack_all_command_tabs()
        self.command_notebook.pack(fill=BOTH, expand=1)

    def bring_to_front(self):
        self.window.focus_force()

    def pack_all_command_tabs(self):
        # Combined commands in one tab
        combined_commands_txt = Text(self.command_notebook)
        combined_commands_txt.tag_config('highlight', foreground='blue')
        for command in self.combined_commands:
            stdin, stdout, stderr = self.ssh.exec_command(command)
            combined_commands_txt.insert(END, ("===== " + command +
                                               " =====\n").encode('utf-8'),
                                         ('highlight', ))
            combined_commands_txt.insert(END, stdout.read())
        self.command_notebook.add(combined_commands_txt, text='Info')

        # Individual commands that get their own tab
        for command in self.command_list:
            stdin, stdout, stderr = self.ssh.exec_command(command)
            command_txt = Text(self.command_notebook)
            command_txt.insert(END, stdout.read())
            self.command_notebook.add(command_txt, text=command)
Exemplo n.º 19
0
Arquivo: CTA.py Projeto: Panumy/CTA-DB
def no_acc():
    global win2, habusrenr
    win2 = Toplevel(root)
    win2.geometry('250x50')
    win2.iconbitmap('Logo.ico')
    win2.resizable(width=FALSE, height=FALSE)
    win2.title("Support")
    habusrlab = Label(win2, text="Full Name")
    habusrenr = Entry(win2)
    habusrbtt = Button(win2, text="Send", command=send_acc_req)
    habusrlab.grid(column=0, row=0)
    habusrenr.grid(column=1, row=0)
    habusrbtt.place(relx=0.6, x=1, y=22.5, anchor=NE)
Exemplo n.º 20
0
class RobView(View):
    GUI_WIDTH = 800
    GUI_HEIGHT = 400
    
    def __init__(self, tkRoot, app, masterComp, parentNode, logger):
        BaseView.__init__(self, tkRoot, app, logger)
        # master (upper level view) component on which this view was issued
        self.masterComp = masterComp
        
        self.parentNode = parentNode
                             
        self.window = Toplevel(self.tkRoot)
        self.window.title("%s" % parentNode.keyForIsObject)
        
        # self.window.bind("<<close-window>>", self.__onClose) # doesn't work
        self.window.protocol("WM_DELETE_WINDOW", self.__onClose)
        
        text = ScrolledText(self.window, width = RobView.GUI_WIDTH,
                            height = RobView.GUI_HEIGHT, background='white')
        text.pack(fill = Y)
        
        # information from ROB (DataChannel) IS object (criteria results)
        # .valueOfIsObject is a bit misleading since it's criteria results
        # checks based on particular values (attributes) within the IS object
        m = ("ROB '%s':\n\n%s" %
             (parentNode.keyForIsObject, parentNode.valueOfIsObject))
        text.insert(END, m)
        
        text.configure(state = DISABLED) # disable edit now, not before insert
        
        # need to store this view under full name (not only under 
        # self.masterComp.name as the other views), since there may be 
        # a number of views named e.g. 'DataChannel0'
        self.app.addActiveView(self.parentNode.keyForIsObject, self)

        
    def createContent(self):
        self.__setWindowGeometry()
        
        
    def __setWindowGeometry(self):
        offsetX = View.ANOTHER_GUI_OFF * self.app.activeViewsCount()
        x = conf.GUI_OFF_X + conf.GUI_WIDTH + offsetX
        geom = "%sx%s+%s+%s" % (RobView.GUI_WIDTH, RobView.GUI_HEIGHT, 
                                x, conf.GUI_OFF_Y)
        self.window.geometry(geom)

        
    def __onClose(self):
        self.app.removeActiveView(self.parentNode.keyForIsObject)
        self.window.destroy()
Exemplo n.º 21
0
    def __init__(self, master, main_window):
        self.master = master
        self.main_window = main_window

        top = Toplevel(master)
        top.title(_("Global Options"))
        top.transient(master)
        top.protocol('WM_DELETE_WINDOW', self.close_dlg)

        top.geometry('%+d%+d' %
                     (master.winfo_rootx() + 100, master.winfo_rooty() + 100))

        self.top = top
        self.build_dlg()
Exemplo n.º 22
0
    def __init__(self, master, main_window):
	self.master = master
	self.main_window = main_window

	top = Toplevel(master)
	top.title(_("Global Options"))
	top.transient(master)
	top.protocol('WM_DELETE_WINDOW', self.close_dlg)

	top.geometry('%+d%+d' % (master.winfo_rootx() + 100,
				 master.winfo_rooty() + 100))

	self.top = top
	self.build_dlg()
Exemplo n.º 23
0
 def __init__(self, master, resultObj, backgroundImg, safetyTimeout,
              frameClass, *frameClassParams, **frameClassNamedParams):
     SysmodalBase.__init__(self, master, backgroundImg, safetyTimeout)
     childWindow = Toplevel(self)
     childWindow.attributes("-topmost", True)
     resultObj.result = frameClass(childWindow, *frameClassParams,
                                   **frameClassNamedParams)
     sw = master.winfo_screenwidth()
     sh = master.winfo_screenheight()
     childWindow.update()
     w = childWindow.winfo_reqwidth()
     h = childWindow.winfo_reqheight()
     childWindow.geometry('%dx%d+%d+%d' %
                          (w, h, sw / 2 - w / 2, sh / 2 - h / 2))
     self._playUACSound()
Exemplo n.º 24
0
class Tooltip_Helper:
    """
  Class to help show tooltips on Tkinter Canvases.
  """
    def __init__(self, canvas):
        """
    |canvas|: the canvas on which tooltips will be shown.
    """
        self._canvas = canvas
        self._tip = None

    def show_tooltip(self, x, y, text, background=TOOLTIP_BACKGROUND):
        """
    Shows a tooltip containing the given |text| close to the point (|x|, |y|) on
        the canvas.
    """
        x += self._canvas.winfo_rootx() + 10
        y += self._canvas.winfo_rooty() + 10
        geometry = '+%d+%d' % (x, y)
        if not self._tip:
            self._tip = Toplevel(self._canvas)
            self._tip.wm_overrideredirect(1)
            self._tip.wm_geometry(geometry)
            try:
                # for Mac OS
                self._tip.tk.call('::tk::unsupported::MacWindowStyle', 'style',
                                  self._tip._w, 'help', 'noActivates')
            except TclError:
                pass
            self.label = Label(self._tip,
                               text=text,
                               justify=LEFT,
                               background=background,
                               relief=SOLID,
                               borderwidth=1,
                               font=DEFAULT_FONT)
            self.label.pack()
        else:
            self._tip.geometry(geometry)
            self.label.config(text=text, background=background)

    def hide_tooltip(self):
        """
    Hides the previously added tooltip, if any.
    """
        if self._tip:
            self._tip.destroy()
            self._tip = None
Exemplo n.º 25
0
def view_stack():
    inputstring = u2_entry.get()
    row, ste, sta, inp, act = process_input(inputstring)
    print inputstring

    show = Toplevel(master)
    show.title("Stack Implementation")
    show.geometry("%dx%d%+d%+d" % (1300, 1300, 0, 0))
    canvas = Canvas(show, width=2000, height=1000)
    canvas.grid(row=0, column=0)
    row = row - 1
    col = 4
    m, a = 10, 10
    n = 100
    b = 125

    for i in range(len(sta)):
        canvas.create_text(a + 60, b + 15, text=i + 1, font="Times 15 bold")
        canvas.create_text(a + 60 + 260,
                           b + 15,
                           text=sta[i],
                           font="Times 15 bold")
        canvas.create_text(a + 60 + 400,
                           b + 15,
                           text=inp[i],
                           font="Times 15 bold")
        canvas.create_text(a + 60 + 660,
                           b + 15,
                           text=act[i],
                           font="Times 15 bold")

        b = b + 30

    for i in range(0, row + 1):
        for j in range(0, col):
            print(m, n)

            canvas.create_rectangle(m, n, m + 200, n + 30)
            m = m + 200
        m = 10
        n = n + 30
    print ste, sta, inp, act
    canvas.create_text(65, 110, text="S.N.", font="Times 15 bold")
    canvas.create_text(285, 110, text="Stack", font="Times 15 bold")
    canvas.create_text(475, 110, text="Input", font="Times 15 bold")
    canvas.create_text(665, 110, text="Action", font="Times 15 bold")

    show.geometry("%dx%d%+d%+d" % (1300, 800, 0, 0))
Exemplo n.º 26
0
def _color_delegator(parent):  # htest #
    from Tkinter import Toplevel, Text
    from idlelib.Percolator import Percolator

    top = Toplevel(parent)
    top.title("Test ColorDelegator")
    top.geometry("200x100+%d+%d" % (parent.winfo_rootx() + 200,
                  parent.winfo_rooty() + 150))
    source = "if somename: x = 'abc' # comment\nprint\n"
    text = Text(top, background="white")
    text.pack(expand=1, fill="both")
    text.insert("insert", source)
    text.focus_set()

    p = Percolator(text)
    d = ColorDelegator()
    p.insertfilter(d)
Exemplo n.º 27
0
def _color_delegator(parent):  # htest #
    from Tkinter import Toplevel, Text
    from idlelib.Percolator import Percolator

    top = Toplevel(parent)
    top.title("Test ColorDelegator")
    top.geometry("200x100+%d+%d" % (parent.winfo_rootx() + 200,
                  parent.winfo_rooty() + 150))
    source = "if somename: x = 'abc' # comment\nprint\n"
    text = Text(top, background="white")
    text.pack(expand=1, fill="both")
    text.insert("insert", source)
    text.focus_set()

    p = Percolator(text)
    d = ColorDelegator('.py')
    p.insertfilter(d)
Exemplo n.º 28
0
def load():
    """
    Handle the load key on the main window.
    """
    def save_select():
        """
        Select key hit.  Set fname and exit if a field is high-lighted.
        """
        sel = mylist.curselection()
        if not sel:
            return
        fname.append(olist[int(sel[0])])
        top.quit()
    olist = sorted(os.listdir(getdir()))
    if len(olist) == 0:
        showwarning('Error', 'No files to load')
        return
    top = Toplevel()
    top.geometry('200x180+800+200')
    fname = []
    top.title('Sudoku Loader')
    tpart = Frame(top)
    tpart.pack(side=Tkinter.TOP)
    bpart = Frame(top)
    bpart.pack(side=Tkinter.BOTTOM)
    scrollbar = Scrollbar(tpart)
    scrollbar.pack(side=Tkinter.RIGHT, fill=Tkinter.Y)
    mylist = Listbox(tpart, yscrollcommand=scrollbar.set)
    for line in olist:
        mylist.insert(Tkinter.END, line)
    mylist.pack(side=Tkinter.LEFT, fill=Tkinter.BOTH)
    scrollbar.config(command=mylist.yview)
    picker = Button(bpart, text='SELECT', command=save_select)
    picker.pack(pady=5)
    top.mainloop()
    if fname:
        retvec = []
        fyle = '%s%s%s' % (getdir(), os.path.sep, fname[0])
        top.destroy()
        with open(fyle, 'r') as infile:
            inline = infile.readline()
            while inline:
                retvec.append(inline.split(':'))
                inline = infile.readline()
            return retvec
Exemplo n.º 29
0
    def about(self):
        """Open an about window.

        Window gives authors, SET version number, and icon credit.
        """
        # Instantiates a new Toplevel about window.
        about_window = Toplevel(self.root)
        about_window.geometry('350x335+25+25')
        about_window.title('About')
        about_window.wm_iconbitmap(constants.ICO)
        about_window.resizable(False, False)

        # Adds text to about window.
        about = Text(about_window, width=50, height=30, padx=10, pady=3)
        about.insert("end", constants.ABOUT)
        about.tag_add("abt", "1.0", "21.30")
        about.tag_config("abt", font='Times 10 bold', justify=CENTER)
        about.pack()
Exemplo n.º 30
0
def _dyn_option_menu(parent):  # htest #
    from Tkinter import Toplevel

    top = Toplevel()
    top.title("Tets dynamic option menu")
    top.geometry("200x100+%d+%d" % (parent.winfo_rootx() + 200,
                  parent.winfo_rooty() + 150))
    top.focus_set()

    var = StringVar(top)
    var.set("Old option set") #Set the default value
    dyn = DynOptionMenu(top,var, "old1","old2","old3","old4")
    dyn.pack()

    def update():
        dyn.SetMenu(["new1","new2","new3","new4"], value="new option set")
    button = Button(top, text="Change option set", command=update)
    button.pack()
Exemplo n.º 31
0
def run():
    """
    Esegue l'emulatore del pdp8
    """
    CD = pdp8()
    principale = Tk()
    principale.title("Pdp8 Emulator : Assembly Editor")
    emulatore = Toplevel()
    emulatore.title("Pdp8 Emulator")
    emulatore.geometry("1015x589")

    edit = Editor(principale, CD)

    scrollbar1 = AutoScrollbar(emulatore)
    scrollbar1.grid(row=0, column=1, sticky=N + S)
    scrollbar2 = AutoScrollbar(emulatore, orient=HORIZONTAL)
    scrollbar2.grid(row=1, column=0, sticky=E + W)

    finestra = Canvas(emulatore,
                      yscrollcommand=scrollbar1.set,
                      xscrollcommand=scrollbar2.set)
    finestra.grid(row=0, column=0, sticky=N + S + E + W)

    scrollbar1.config(command=finestra.yview)
    scrollbar2.config(command=finestra.xview)

    emulatore.grid_rowconfigure(0, weight=1)
    emulatore.grid_columnconfigure(0, weight=1)

    emul = Emulatore(finestra, edit, CD, emulatore)

    finestra.create_window(0, 0, anchor=NW, window=emul.master)

    emul.master.update_idletasks()

    finestra.config(scrollregion=finestra.bbox("all"))

    principale.protocol("WM_DELETE_WINDOW", edit.exit)
    emulatore.protocol("WM_DELETE_WINDOW", emul.exit)

    principale.mainloop()
    emulatore.mainloop()
Exemplo n.º 32
0
def run():
    """
    Esegue l'emulatore del pdp8
    """
    CD = pdp8()
    principale = Tk()
    principale.title("Pdp8 Emulator : Assembly Editor")
    emulatore = Toplevel()
    emulatore.title("Pdp8 Emulator")
    emulatore.geometry("1015x589")

    edit = Editor(principale, CD)

    scrollbar1 = AutoScrollbar(emulatore)
    scrollbar1.grid(row=0, column=1, sticky=N + S)
    scrollbar2 = AutoScrollbar(emulatore, orient=HORIZONTAL)
    scrollbar2.grid(row=1, column=0, sticky=E + W)

    finestra = Canvas(emulatore,
                      yscrollcommand=scrollbar1.set,
                      xscrollcommand=scrollbar2.set)
    finestra.grid(row=0, column=0, sticky=N + S + E + W)

    scrollbar1.config(command=finestra.yview)
    scrollbar2.config(command=finestra.xview)

    emulatore.grid_rowconfigure(0, weight=1)
    emulatore.grid_columnconfigure(0, weight=1)

    emul = Emulatore(finestra, edit, CD, emulatore)

    finestra.create_window(0, 0, anchor=NW, window=emul.master)

    emul.master.update_idletasks()

    finestra.config(scrollregion=finestra.bbox("all"))

    principale.protocol("WM_DELETE_WINDOW", edit.exit)
    emulatore.protocol("WM_DELETE_WINDOW", emul.exit)

    principale.mainloop()
    emulatore.mainloop()
Exemplo n.º 33
0
 def loginCommand(self, username, password):
     if self.gui.btd.database.login(username, password):
         self.gui.screenChange(welcomePage(self.root, self.gui))
     else:
         popup = Toplevel()
         popup.title("Incorrect")
         
         windowWidth = popup.winfo_screenwidth()
         windowHeight = popup.winfo_screenheight()
         
         width = .25 * windowWidth
         height = .1 * windowHeight
         x = (windowWidth - width) / 2
         y = (windowHeight - height) / 2
         
         popup.geometry("%dx%d+%d+%d" % (width, height, x, y))
         popup.update()
         
         Label(popup, text="Incorrect username or password!").pack()
         Button(popup, text="Dismiss", command=popup.destroy).pack()
Exemplo n.º 34
0
    def about(self):
        """
        Simple TopLevel window displaying the authors
        """
        logger.info('Opening about window')
        file_window = Toplevel(self.__root)
        file_window.geometry("300x300")
        file_window.title('About')

        text = Text(file_window)
        text.insert(END, constants.ABOUT)
        text.config(state=DISABLED)
        text.pack(expand=True, fill=BOTH)

        button_close = Button(file_window,
                              text='Close',
                              command=file_window.destroy)
        button_close.pack()

        center(file_window, (300, 300))
Exemplo n.º 35
0
class Tooltip_Helper:
  """
  Class to help show tooltips on Tkinter Canvases.
  """
  def __init__(self, canvas):
    """
    |canvas|: the canvas on which tooltips will be shown.
    """
    self._canvas = canvas
    self._tip = None
  def show_tooltip(self, x, y, text, background=TOOLTIP_BACKGROUND):
    """
    Shows a tooltip containing the given |text| close to the point (|x|, |y|) on
        the canvas.
    """
    x += self._canvas.winfo_rootx() + 10
    y += self._canvas.winfo_rooty() + 10
    geometry = '+%d+%d' % (x, y)
    if not self._tip:
      self._tip = Toplevel(self._canvas)
      self._tip.wm_overrideredirect(1)
      self._tip.wm_geometry(geometry)
      try:
        # for Mac OS
        self._tip.tk.call('::tk::unsupported::MacWindowStyle', 'style',
            self._tip._w, 'help', 'noActivates')
      except TclError:
        pass
      self.label = Label(self._tip, text=text, justify=LEFT,
          background=background, relief=SOLID, borderwidth=1, font=DEFAULT_FONT)
      self.label.pack()
    else:
      self._tip.geometry(geometry)
      self.label.config(text=text, background=background)
  def hide_tooltip(self):
    """
    Hides the previously added tooltip, if any.
    """
    if self._tip:
      self._tip.destroy()
      self._tip = None
Exemplo n.º 36
0
    def createUser(self, username, password, fname, lname):
        if self.gui.btd.database.newUser(username, password, fname, lname):
            popup = Toplevel()
            popup.title("Account created!")

            windowWidth = popup.winfo_screenwidth()
            windowHeight = popup.winfo_screenheight()

            width = .25 * windowWidth
            height = .1 * windowHeight
            x = (windowWidth - width) / 2
            y = (windowHeight - height) / 2

            popup.geometry("%dx%d+%d+%d" % (width, height, x, y))
            popup.update()

            Label(
                popup,
                text="Your new account has been successfully created!").pack()
            Button(popup, text="Dismiss", command=popup.destroy).pack()

            self.gui.screenChange(title.titlePage(self.root, self.gui))
        else:
            popup = Toplevel()
            popup.title("Username Exists!")

            windowWidth = popup.winfo_screenwidth()
            windowHeight = popup.winfo_screenheight()

            width = .25 * windowWidth
            height = .1 * windowHeight
            x = (windowWidth - width) / 2
            y = (windowHeight - height) / 2

            popup.geometry("%dx%d+%d+%d" % (width, height, x, y))
            popup.update()

            Label(popup,
                  text="A user account with that username already exists!"
                  ).pack()
            Button(popup, text="Dismiss", command=popup.destroy).pack()
Exemplo n.º 37
0
    def Winning(self, color):
        self.someoneWin = True
        window = Toplevel(self.master, background="#f0e5df")
        window.attributes('-topmost', True)
        window.title("we have a winner!")
        window.geometry("300x200")

        message = Label(window,
                        text="The winner is \n" + str(color),
                        background="#f0e5df",
                        font=("Courier", 20))
        message.place(x=150, y=80, anchor="center")

        resetButton = Button(window,
                             text="Reset Game",
                             command=lambda:
                             ((self.ResetGame()), (window.destroy()),
                              (self.master.attributes('-topmost', True))),
                             height=2,
                             width=15)

        resetButton.place(x=150, y=160, anchor="center")
        center(window)
Exemplo n.º 38
0
 def createUser(self, username, password, fname, lname):
     if self.gui.btd.database.newUser(username, password, fname, lname):
         popup = Toplevel()
         popup.title("Account created!")
         
         windowWidth = popup.winfo_screenwidth()
         windowHeight = popup.winfo_screenheight()
         
         width = .25 * windowWidth
         height = .1 * windowHeight
         x = (windowWidth - width) / 2
         y = (windowHeight - height) / 2
         
         popup.geometry("%dx%d+%d+%d" % (width, height, x, y))
         popup.update()
         
         Label(popup, text="Your new account has been successfully created!").pack()
         Button(popup, text="Dismiss", command=popup.destroy).pack()
         
         self.gui.screenChange(title.titlePage(self.root, self.gui))
     else:
         popup = Toplevel()
         popup.title("Username Exists!")
         
         windowWidth = popup.winfo_screenwidth()
         windowHeight = popup.winfo_screenheight()
         
         width = .25 * windowWidth
         height = .1 * windowHeight
         x = (windowWidth - width) / 2
         y = (windowHeight - height) / 2
         
         popup.geometry("%dx%d+%d+%d" % (width, height, x, y))
         popup.update()
         
         Label(popup, text="A user account with that username already exists!").pack()
         Button(popup, text="Dismiss", command=popup.destroy).pack()
Exemplo n.º 39
0
def subVentana(stringExpresionBooleana, ventanaPrincipal):
    ventanaHija = Toplevel(ventanaPrincipal)
    ventanaHija.geometry("300x250")
    ventanaHija.title("Mapa de Karnaugh")

    matrizExpresionBooleana, variables = generarMatrizExpresionBooleana(
        stringExpresionBooleana.get())
    mapaKarnaugh = llenarMapaKarnaugh(matrizExpresionBooleana)

    # print mapa
    if len(variables) == 4:
        mapa1 = str(mapaKarnaugh[0])
        mapa2 = str(mapaKarnaugh[1])
        mapa3 = str(mapaKarnaugh[2])
        mapa4 = str(mapaKarnaugh[3])
        Label(ventanaHija, text="Mapa de Karnaugh").grid(row=2, column=2)
        Label(ventanaHija, text=mapa1).grid(row=4, column=2)
        Label(ventanaHija, text=mapa2).grid(row=5, column=2)
        Label(ventanaHija, text=mapa3).grid(row=6, column=2)
        Label(ventanaHija, text=mapa4).grid(row=7, column=2)
    else:
        mapa1 = str(mapaKarnaugh[0])
        mapa2 = str(mapaKarnaugh[1])
        Label(ventanaHija, text="Mapa de Karnaugh").grid(row=2, column=2)
        Label(ventanaHija, text=mapa1).grid(row=4, column=2)
        Label(ventanaHija, text=mapa2).grid(row=5, column=2)

    #print expresion
    gruposDe1 = leerMapaKarnaugh(mapaKarnaugh)
    matrizCambioDeEstados = identificarEstados(gruposDe1, len(variables))
    expresionSimplificada = generarExpresionSimplificada(
        matrizCambioDeEstados, variables)
    Label(ventanaHija,
          text="expresion: " + expresionSimplificada).grid(row=8, column=2)

    ventanaHija.mainloop()
Exemplo n.º 40
0
class robotGUI():
    def __init__(self):

        #Initialize the master window 
        self.main = tk.Tk()
        self.main.title("Robot Interface v0.24")
        self.main.geometry("850x650+300+300")
        self.main.resizable(width=False, height=False)
        
        menubar = Menu(self.main)
        self.main.config(menu=menubar)
        
        preferenceMenu = Menu(menubar)
        preferenceMenu.add_command(label="Controller Settings", \
            command = self.createControllerWindow)
        helpMenu = Menu(menubar)
        helpMenu.add_command(label="Help...")
        comMenu = Menu(menubar)
        comMenu.add_command(label="Empty")
        fileMenu = Menu(menubar)
        fileMenu.add_command(label="Data Files...")

        menubar.add_cascade(label="File", menu=fileMenu)
        menubar.add_cascade(label="Preferences", menu=preferenceMenu)
        menubar.add_cascade(label="COM Port", menu=comMenu)
        menubar.add_cascade(label="Help", menu=helpMenu)

        #Initialize frame sections of the window
        self.titleFrame = tk.Frame()
        self.enableDisableFrame = tk.Frame()
        self.labelFrame = tk.Frame()

        #Frame partitions (subframes) go here
        self.enableDisable=tk.Frame(self.enableDisableFrame,width=129,height=87)
        self.enableDisable.pack_propagate(0)
        self.axisLabels=tk.Frame(self.labelFrame,width=130,height=200)
        self.axisLabels.pack_propagate(0)
        self.buttonLabels=tk.Frame(self.labelFrame,width=130,height=323)
        self.buttonLabels.pack_propagate(0)

        #Initialize the variables
        self.xAxisVar = tk.StringVar(value = "xAxis is: N/A")
        self.yAxisVar = tk.StringVar(value = "yAxis is: N/A")
        self.aAxisVar = tk.StringVar(value = "aAxis is: N/A")
        self.bAxisVar = tk.StringVar(value = "bAxis is: N/A")

        #Initialize buttons
        self.remote_Label = tk.Label(self.enableDisable, text='PS3 Controller',\
            font=("Helvetica", 13), fg='black', anchor = tk.CENTER, width = 12)
        self.remote_Label.pack(side = "top")

        self.initBut = tk.Button(self.enableDisable, text ="Enable", \
            command = self.runController, width = 15)
        self.initBut.pack()

        self.stopBut = tk.Button(self.enableDisable, text ="Disable", \
            command = self.stopController, width = 15)
        self.stopBut.pack()

        #Initalize Axis Labels
        self.title_label = tk.Label(self.titleFrame, text='Mech Warfare GUI',\
            font=("Helvetica", 20),bg='blue',fg='white', width = 53) 

        self.axisTitle = tk.Label(self.axisLabels, text='Axes',\
            font=("Helvetica", 13), fg='black', width = 40, \
            anchor=tk.CENTER) 

        self.xAxisLabel = tk.Label(self.axisLabels, fg="black", \
            textvariable=self.xAxisVar, width=40, font=("Helvetica", 12), \
            anchor=tk.W)

        self.yAxisLabel = tk.Label(self.axisLabels, fg="black", \
            textvariable=self.yAxisVar, width=40, font=("Helvetica", 12), \
            anchor=tk.W)

        self.aAxisLabel = tk.Label(self.axisLabels, fg="black", \
            textvariable=self.aAxisVar, width=40, font=("Helvetica", 12), \
            anchor=tk.W)

        self.bAxisLabel = tk.Label(self.axisLabels, fg="black", \
            textvariable=self.bAxisVar, width=40, font=("Helvetica", 12), \
            anchor=tk.W)

        #Initalize Button Labels
        self.buttonTitle = tk.Label(self.buttonLabels, text='Buttons',\
            font=("Helvetica", 13), fg='black', width = 40, \
            anchor=tk.CENTER) 

        self.xLabel = tk.Label(self.buttonLabels, text=' X ',\
            font=("Helvetica", 12), fg='black', bg='red', width = 30, \
            anchor=tk.CENTER) 

        self.cirLabel = tk.Label(self.buttonLabels, text=' Circle ',\
            font=("Helvetica", 12), fg='black', bg='red', width = 30, \
            anchor=tk.CENTER) 

        self.triLabel = tk.Label(self.buttonLabels, text=' Triangle ',\
            font=("Helvetica", 12), fg='black', bg='red', width = 30, \
            anchor=tk.CENTER) 

        self.squLabel = tk.Label(self.buttonLabels, text=' Square ',\
            font=("Helvetica", 12), fg='black', bg='red', width = 30, \
            anchor=tk.CENTER) 

        self.leftTrigLabel = tk.Label(self.buttonLabels, text='Left Trigger',\
            font=("Helvetica", 12), fg='black', bg='red', width = 30, \
            anchor=tk.CENTER)

        self.rightTrigLabel = tk.Label(self.buttonLabels, text='Right Trigger',\
            font=("Helvetica", 12), fg='black', bg='red', width = 30, \
            anchor=tk.CENTER)

        self.leftBumpLabel = tk.Label(self.buttonLabels, text='Left Bumper',\
            font=("Helvetica", 12), fg='black', bg='red', width = 30, \
            anchor=tk.CENTER)

        self.rightBumpLabel = tk.Label(self.buttonLabels, text='Right Bumper',\
            font=("Helvetica", 12), fg='black', bg='red', width = 30, \
            anchor=tk.CENTER)

        self.selectLabel = tk.Label(self.buttonLabels, text='Select',\
            font=("Helvetica", 12), fg='black', bg='red', width = 30, \
            anchor=tk.CENTER)

        self.startLabel = tk.Label(self.buttonLabels, text='Start',\
            font=("Helvetica", 12), fg='black', bg='red', width = 30, \
            anchor=tk.CENTER)

        self.rightTogLabel = tk.Label(self.buttonLabels, text='Right Toggle',\
            font=("Helvetica", 12), fg='black', bg='red', width = 30, \
            anchor=tk.CENTER)

        self.leftTogLabel = tk.Label(self.buttonLabels, text='Left Toggle',\
            font=("Helvetica", 12), fg='black', bg='red', width = 30, \
            anchor=tk.CENTER)

        self.title_label.pack()
        self.axisTitle.pack()
        self.xAxisLabel.pack()
        self.yAxisLabel.pack()
        self.aAxisLabel.pack()
        self.bAxisLabel.pack()
        self.buttonTitle.pack()
        self.xLabel.pack()
        self.cirLabel.pack()
        self.triLabel.pack()
        self.squLabel.pack()
        self.leftTrigLabel.pack()
        self.rightTrigLabel.pack()
        self.leftBumpLabel.pack()
        self.rightBumpLabel.pack()
        self.rightTogLabel.pack()
        self.leftTogLabel.pack()
        self.selectLabel.pack()
        self.startLabel.pack()

        #Package subframes go here
        self.axisLabels.pack()
        self.buttonLabels.pack()
        self.enableDisable.pack()

        #Package frames and create the window
        self.titleFrame.pack()
        self.enableDisableFrame.pack()
        self.labelFrame.pack()

        self.enableDisableFrame.place(x=6, y=42)
        self.labelFrame.place(x=5, y=129)

        self.axisLabels.config(highlightbackground="black", borderwidth= 5, \
            relief = "ridge")
        self.buttonLabels.config(highlightbackground="black", borderwidth= 5, \
            relief = "ridge")
        self.enableDisable.config(highlightbackground="black", borderwidth= 5, \
            relief = "ridge")

        tk.mainloop()

    def createControllerWindow(self):

        #Creation of the main window
        self.controllerWindow = Toplevel()
        self.controllerWindow.title("Controller Settings")
        self.controllerWindow.geometry("400x310+300+300")
        self.controllerWindow.resizable(width=False, height=False)

        #Frame for the manual controller options
        self.k_controllerFrame = tk.Frame(self.controllerWindow)
        self.c_controllerFrame = tk.Frame(self.controllerWindow)
        self.instructionFrame = tk.Frame(self.controllerWindow)

        self.knownJsFrame=tk.Frame(self.k_controllerFrame,width=150,height=120)
        self.knownJsFrame.pack_propagate(0)
        self.chosenJsFrame=tk.Frame(self.c_controllerFrame,width=150,height=120)
        self.chosenJsFrame.pack_propagate(0)

        self.instrLabel = tk.Label(self.instructionFrame, text="Please select up " \
            "to two remote controllers from the recognized controller list. Alter" \
            "natively, scan for existing controllers and automatically add the " \
            "controller to the software.", anchor=tk.W, justify=tk.LEFT, wraplength = 400)
        self.instrLabel.pack()
        self.l1 = tk.Label(self.knownJsFrame, text="Recognized Controllers")
        self.l1.pack()
        self.l2 = tk.Label(self.chosenJsFrame, text="Selected Controller/s")
        self.l2.pack()
        self.knownListbox = tk.Listbox(self.knownJsFrame, height = 15, width = 29)
        self.knownListbox.insert(tk.END)

        for item in ["PS3 PowerA", "Xbox 360 Afterglow"]:
            self.knownListbox.insert(tk.END, item)

        self.chosenListbox = tk.Listbox(self.chosenJsFrame, height = 15, width = 29)
        self.chosenListbox.insert(tk.END)

        self.closeBtn = tk.Button(self.controllerWindow, text ="Close", \
            command = self.controllerWindow.destroy, width = 12)

        self.okBtn = tk.Button(self.controllerWindow, text ="Okay", \
            width = 12)

        self.applyBtn = tk.Button(self.controllerWindow, text ="Apply Changes", \
            width = 16)

        self.addBtn = tk.Button(self.controllerWindow, text ="Add", \
            width = 10, command = self.addListBoxIndex)

        self.rmvBtn = tk.Button(self.controllerWindow, text ="Remove", \
            width = 10, command = self.rmvListBoxIndex)

        self.scanBtn = tk.Button(self.controllerWindow, text ="Scan for controllers...", \
            width = 16)

        self.knownListbox.pack()
        self.chosenListbox.pack()
        self.knownJsFrame.pack()
        self.chosenJsFrame.pack()
        self.instructionFrame.pack()
        self.k_controllerFrame.pack()
        self.c_controllerFrame.pack()
        self.closeBtn.pack()
        self.okBtn.pack()
        self.applyBtn.pack()
        self.addBtn.pack()
        self.rmvBtn.pack()
        self.scanBtn.pack()

        self.k_controllerFrame.place(x = 20, y = 85)
        self.c_controllerFrame.place(x = 210, y = 85)

        self.closeBtn.place(x = 300, y = 275)
        self.okBtn.place(x = 200, y = 275)
        self.applyBtn.place(x = 20, y = 275)
        self.addBtn.place(x = 40, y = 210)
        self.rmvBtn.place(x = 240, y = 210)
        self.scanBtn.place(x = 230, y = 50)

    def addListBoxIndex(self):

        self.chosenInt = 0
        self.chosenInt = self.chosenListbox.size()

        if self.chosenInt >= 2:
            tkm.showerror("Error", "You can only add up to two controllers.")
        else:
            self.listBoxStr = ""
            self.listBoxStr = self.knownListbox.get(tk.ACTIVE)

            self.chosenListbox.insert(tk.END, self.listBoxStr)

    def rmvListBoxIndex(self):

        self.chosenInt = 0
        self.chosenInt = self.chosenListbox.index(tk.ACTIVE)

        self.chosenListbox.delete(self.chosenInt)

    def initController(self):

        pygame.init()

        ### Tells the number of joysticks/error detection
        joystick_count = pygame.joystick.get_count()
        print ("There is ", joystick_count, "joystick/s")
        if joystick_count == 0:
            print ("Error, I did not find any joysticks")
            tkm.showerror("Error", "Please connect a remote controller.")
        else:
            my_joystick = pygame.joystick.Joystick(0)
            jsName = my_joystick.get_name
            print(jsName)
            my_joystick.init()
            self.js = my_joystick

    def stopController(self):

        self.js.quit()

    def runController(self):
        self.initController()
        while True:
            pygame.event.pump()
            axes = self.updateAxes()
            buttons = self.updateButtons()

            self.xAxisVar.set(value="xAxis is: %(xaxis)s" %{'xaxis':str(axes['X-Axis1'])})
            self.yAxisVar.set(value="yAxis is: %(xaxis)s" %{'xaxis':str(axes['Y-Axis1'])})
            self.aAxisVar.set(value="aAxis is: %(xaxis)s" %{'xaxis':str(axes['X-Axis2'])})
            self.bAxisVar.set(value="bAxis is: %(xaxis)s" %{'xaxis':str(axes['Y-Axis2'])})

            if buttons['xButton'] == 1:
                self.xLabel.configure(bg = 'green')
            elif buttons['xButton'] == 0:
                self.xLabel.configure(bg = 'red')

            if buttons['circleButton'] == 1:
                self.cirLabel.configure(bg = 'green')
            elif buttons['circleButton'] == 0:
                self.cirLabel.configure(bg = 'red')

            if buttons['triangleButton'] == 1:
                self.triLabel.configure(bg = 'green')
            elif buttons['triangleButton'] == 0:
                self.triLabel.configure(bg = 'red')

            if buttons['squareButton'] == 1:
                self.squLabel.configure(bg = 'green')
            elif buttons['squareButton'] == 0:
                self.squLabel.configure(bg = 'red')

            if buttons['leftTrigger'] == 1:
                self.leftTrigLabel.configure(bg = 'green')
            elif buttons['leftTrigger'] == 0:
                self.leftTrigLabel.configure(bg = 'red')

            if buttons['rightTrigger'] == 1:
                self.rightTrigLabel.configure(bg = 'green')
            elif buttons['rightTrigger'] == 0:
                self.rightTrigLabel.configure(bg = 'red')

            if buttons['leftBumper'] == 1:
                self.leftBumpLabel.configure(bg = 'green')
            elif buttons['leftBumper'] == 0:
                self.leftBumpLabel.configure(bg = 'red')

            if buttons['rightBumper'] == 1:
                self.rightBumpLabel.configure(bg = 'green')
            elif buttons['rightBumper'] == 0:
                self.rightBumpLabel.configure(bg = 'red')

            if buttons['selectButton'] == 1:
                self.selectLabel.configure(bg = 'green')
            elif buttons['selectButton'] == 0:
                self.selectLabel.configure(bg = 'red')

            if buttons['startButton'] == 1:
                self.startLabel.configure(bg = 'green')
            elif buttons['startButton'] == 0:
                self.startLabel.configure(bg = 'red')

            if buttons['rightToggle'] == 1:
                self.rightTogLabel.configure(bg = 'green')
            elif buttons['rightToggle'] == 0:
                self.rightTogLabel.configure(bg = 'red')

            if buttons['leftToggle'] == 1:
                self.leftTogLabel.configure(bg = 'green')
            elif buttons['leftToggle'] == 0:
                self.leftTogLabel.configure(bg = 'red')

            self.labelFrame.update()

            pygame.time.wait(100)

    def updateAxes(self):

        controllerDict = {'X-Axis1': 0, 'Y-Axis2': 0, 'X-Axis2': 0, 'Y-Axis2': 0};

        xAxis = self.js.get_axis(0) 
        yAxis = self.js.get_axis(1) * -1
        aAxis = self.js.get_axis(2)
        bAxis = self.js.get_axis(3) * -1

        if xAxis < 0.1 and xAxis > -0.1:
            xAxis = 0
        if yAxis < 0.1 and yAxis > -0.1:
            yAxis = 0
        if aAxis < 0.1 and aAxis > -0.1:
            aAxis = 0
        if bAxis < 0.1 and bAxis > -0.1:
            bAxis = 0

        xAxis = math.ceil(xAxis*10000)/10000
        yAxis = math.ceil(yAxis*10000)/10000
        aAxis = math.ceil(aAxis*10000)/10000
        bAxis = math.ceil(bAxis*10000)/10000

        print 'X-Axis 1: ' + str(xAxis) + '  Y-Axis 1: ' + str(yAxis)
        print 'X-Axis 2: ' + str(aAxis) + '  Y-Axis 2: ' + str(bAxis)

        controllerDict['X-Axis1'] = xAxis;
        controllerDict['Y-Axis1'] = yAxis;
        controllerDict['X-Axis2'] = aAxis;
        controllerDict['Y-Axis2'] = bAxis;

        print "dict['X-Axis1']: ", controllerDict['X-Axis1'];

        return controllerDict

    def updateButtons(self):

        buttonDict = {'xButton': 0, 'circleButton': 0, 'triangleButton': 0, 'squareButton': 0,
        'leftBumper': 0, 'rightBumper': 0, 'leftTrigger': 0, 'rightTrigger': 0,
        'selectButton': 0, 'startButton': 0, 'leftToggle': 0, 'rightToggle': 0,};

        xButton = self.js.get_button(1)
        circleButton = self.js.get_button(2)
        triangleButton = self.js.get_button(3)
        squareButton = self.js.get_button(0)
        leftBumper = self.js.get_button(4)
        rightBumper = self.js.get_button(5)
        leftTrigger = self.js.get_button(6)
        rightTrigger = self.js.get_button(7)
        selectButton = self.js.get_button(8)
        startButton = self.js.get_button(9)
        leftToggle = self.js.get_button(10)
        rightToggle = self.js.get_button(11)

        print 'X Button is: ' + str(xButton) + '  Circle Button is: ' + str(circleButton)
        print 'Triangle Button is: ' + str(triangleButton) + '  Square Button is: ' + str(squareButton)
        print 'Left Bumper is: ' + str(leftBumper) + '  Right Bumper is: ' + str(rightBumper)
        print 'Left Trigger is: ' + str(leftTrigger) + '  Right Trigger is: ' + str(rightTrigger)
        print 'Select Button is: ' + str(selectButton) + '  Start Button is: ' + str(startButton)
        print 'Left Toggle is: ' + str(leftToggle) + '  Right Toggle is: ' + str(rightToggle)

        buttonDict['xButton'] = xButton;
        buttonDict['circleButton'] = circleButton;
        buttonDict['triangleButton'] = triangleButton;
        buttonDict['squareButton'] = squareButton;
        buttonDict['leftBumper'] = leftBumper;
        buttonDict['rightBumper'] = rightBumper;
        buttonDict['leftTrigger'] = leftTrigger;
        buttonDict['rightTrigger'] = rightTrigger;
        buttonDict['selectButton'] = selectButton;
        buttonDict['startButton'] = startButton;
        buttonDict['leftToggle'] = leftToggle;
        buttonDict['rightToggle'] = rightToggle;

        print "dict['xButton']: ", buttonDict['xButton'];

        return buttonDict
def inicio(c):
    global ventana2, Labeli, Labelt, img0, img1, imgF, row, cont
    instruction=None
    img0=PhotoImage(file="00.gif") # Reads photos
    img00=PhotoImage(file="0000.gif")
    imgF=PhotoImage(file="FF.gif")

    if c:  
        ventana2=Toplevel(ventana)
        ventana2.title("MANITOR")
        ventana2.configure(bg="white")
        ventana2.geometry("1000x600+5+40")
    
        Labelt=Label(ventana2,text='BIENVENIDO ', # ventana2 TEXTO
                fg="black",bg="white",font=("Helvetica 36 "))
        ventana2.columnconfigure(0,weight=1)
        Labelt.grid(row=1,column=0)
        Labeli=Label(ventana2,image=img00) # ventana2 IMAGEN
        Labeli.grid(row=2,column=0)
                
    else:
        Labelt.config(text='BIENVENIDO ')
        Labeli.image = img00
        Labeli.config(image=img00)
    ventana.iconify() # Turns window into an icon
    
    row=row+1
    cont=cont+1

    

    
    while 1:
        
        nuevoUsuario = detectUser.newUser(3,lower,upper)
        
    
        Labelt.config(text='BIENVENIDO \n  Por favor moje sus manos con agua')
        worksheet.write_datetime(row, col, date_time,f2)
        worksheet.write_datetime(row, col+1, date_time,f3)
        worksheet.write(row, col +2, cont, f6)
        worksheet.write(row, col +3, 'NUEVA PERSONA',f4)
        ventana2.update()
        video000()


        jabon()        

        primero1()
            
####################### fin instrucciones

        Labeli=Label(ventana2,image=img00)
        Labeli.grid(row=2,column=0)
        Labelt.config(text='Sus manos son seguras')
        row=row+1
        worksheet.write_datetime(row, col, date_time, f2)
        worksheet.write_datetime(row, col+1, date_time,f3)
        worksheet.write(row, col +3, 'TERMINO')
        ventana2.update()
        ventana2.after(2000)
Exemplo n.º 42
0
class KeyboardEntry:
    """Mixin class that can be used to add the ability to type values for
widget.  When the cursor enters the widget the focus is set to the widget
and the widget that had the focus previousy is saved in .lastFocus.
When the cursor leaves the widget focus is restored to self.lastFocus.

key_cb(event) is called upon KeyRelease events. If this is the first keytroke
an undecorated window is created next to the cursor and handleKeyStroke(event)
is called.  This method should be subclassed to modify the way the string is
typed in (see thumbwheel.py for an example of handling numbers only).
When the Return key is pressed, the entry window is destroyed and if the
typed striong is not empty self.callSet(self.typedValue) is called.

If the cursor moves out of the widget before Rrturn is pressed the value
in the entry window is discarded and the entry window is destroyed.
"""
    def __init__(self, widgets, callSet):
        # callSet is a function taking one argument (string) which will be
        # when the Returnm key is hit (if the typed string is not empty)
        # widgets is a list of Tkinter wigets for which <Enter>, <Leave>
        # <Return> and <KeyRelease> are handled. These widgets has to exist
        # before thsi constructor can be called
        assert callable(callSet)
        self.callSet = callSet
        for w in widgets:
            w.bind("<Enter>", self.enter_cb)
            w.bind("<Leave>", self.leave_cb)
            w.bind("<Return>", self.return_cb)
            w.bind("<KeyRelease>", self.key_cb)

        self.typedValue = '' # string accumulating valuescharacters typed
        self.lastFocus = None # widget to which the focus will be restored
                              # when the mouse leaves the widget
        self.topEntry = None # top level for typing values
        self.typedValueTK = None #Tk label used as entry for value


    def key_cb(self, event=None):
        # call back function for keyboard events (except for Return)
        # handle numbers to set value
        key = event.keysym
        if key=='Return': return

        #print 'Key:', key
        if len(self.typedValue)==0 and self.topEntry is None:
            # create Tk label showing typed value
            x = event.x
            y = event.y

            #print 'create entry'
            self.topEntry = Toplevel()
            self.topEntry.overrideredirect(1)
            w = event.widget
            if event.x >= 0:
                self.topEntry.geometry('+%d+%d'%(w.winfo_rootx() + event.x+10,
                                                 w.winfo_rooty() + event.y))
            else:
                self.topEntry.geometry('+%d+%d'%(w.winfo_rootx() +10,
                                                 w.winfo_rooty() ))
            self.typedValueTK = Label(
                master=self.topEntry, text='', relief='sunken', bg='yellow')
            self.typedValueTK.pack()

        self.handleKeyStroke(event)
        

    def leave_cb(self, event=None):
        # make sure widget gets keyboard events
        # print 'leave', event.widget

        if self.topEntry:
            self.typedValueTK.destroy()
            self.topEntry.destroy()
            self.topEntry = None
        self.typedValue = ''
        if self.lastFocus:
            #print 'restoring focus'
            if widgetsOnBackWindowsCanGrabFocus is False:
                lActiveWindow = self.lastFocus.focus_get()
                if    lActiveWindow is not None \
                  and ( lActiveWindow.winfo_toplevel() != self.lastFocus.winfo_toplevel() ):
                    return

            self.lastFocus.focus_set()
            self.lastFocus = None
            event.widget.config(cursor='')


    def enter_cb(self, event=None):
        # make sure widget gets keyboard events
        #print 'enter', event.widget

        if widgetsOnBackWindowsCanGrabFocus is False:
            lActiveWindow = event.widget.focus_get()
            if    lActiveWindow is not None \
              and ( lActiveWindow.winfo_toplevel() != event.widget.winfo_toplevel() ):
                return

        if self.lastFocus is None:
            #print 'setting focus'
            self.lastFocus = self.focus_lastfor()
        event.widget.focus_set()
        event.widget.config(cursor='xterm')


    def return_cb(self, event):
        # return should destroy the topEntry
        #print "return_cb"
        if self.typedValueTK is not None:
            self.typedValueTK.destroy()
        if self.topEntry is not None:
            self.topEntry.destroy()
        self.topEntry = None
        if len(self.typedValue):
            #print 'setting to', self.type(self.typedValue)
            self.callSet(self.typedValue)
        self.typedValue = ''


    ## TO BE SUBCLASSED

    def handleKeyStroke(self, event):
        # by default we handle delete character keys
        key = event.keysym
        if key=='BackSpace' or key=='Delete':
            self.typedValue = self.typedValue[:-1]
            self.typedValueTK.configure(text=self.typedValue)
Exemplo n.º 43
0
class KeyboardEntry:
    """Mixin class that can be used to add the ability to type values for
widget.  When the cursor enters the widget the focus is set to the widget
and the widget that had the focus previousy is saved in .lastFocus.
When the cursor leaves the widget focus is restored to self.lastFocus.

key_cb(event) is called upon KeyRelease events. If this is the first keytroke
an undecorated window is created next to the cursor and handleKeyStroke(event)
is called.  This method should be subclassed to modify the way the string is
typed in (see thumbwheel.py for an example of handling numbers only).
When the Return key is pressed, the entry window is destroyed and if the
typed striong is not empty self.callSet(self.typedValue) is called.

If the cursor moves out of the widget before Rrturn is pressed the value
in the entry window is discarded and the entry window is destroyed.
"""
    def __init__(self, widgets, callSet):
        # callSet is a function taking one argument (string) which will be
        # when the Returnm key is hit (if the typed string is not empty)
        # widgets is a list of Tkinter wigets for which <Enter>, <Leave>
        # <Return> and <KeyRelease> are handled. These widgets has to exist
        # before thsi constructor can be called
        assert callable(callSet)
        self.callSet = callSet
        for w in widgets:
            w.bind("<Enter>", self.enter_cb)
            w.bind("<Leave>", self.leave_cb)
            w.bind("<Return>", self.return_cb)
            w.bind("<KeyRelease>", self.key_cb)

        self.typedValue = ''  # string accumulating valuescharacters typed
        self.lastFocus = None  # widget to which the focus will be restored
        # when the mouse leaves the widget
        self.topEntry = None  # top level for typing values
        self.typedValueTK = None  #Tk label used as entry for value

    def key_cb(self, event=None):
        # call back function for keyboard events (except for Return)
        # handle numbers to set value
        key = event.keysym
        if key == 'Return': return

        #print 'Key:', key
        if len(self.typedValue) == 0 and self.topEntry is None:
            # create Tk label showing typed value
            x = event.x
            y = event.y

            #print 'create entry'
            self.topEntry = Toplevel()
            self.topEntry.overrideredirect(1)
            w = event.widget
            if event.x >= 0:
                self.topEntry.geometry('+%d+%d' %
                                       (w.winfo_rootx() + event.x + 10,
                                        w.winfo_rooty() + event.y))
            else:
                self.topEntry.geometry('+%d+%d' %
                                       (w.winfo_rootx() + 10, w.winfo_rooty()))
            self.typedValueTK = Label(master=self.topEntry,
                                      text='',
                                      relief='sunken',
                                      bg='yellow')
            self.typedValueTK.pack()

        self.handleKeyStroke(event)

    def leave_cb(self, event=None):
        # make sure widget gets keyboard events
        # print 'leave', event.widget

        if self.topEntry:
            self.typedValueTK.destroy()
            self.topEntry.destroy()
            self.topEntry = None
        self.typedValue = ''
        if self.lastFocus:
            #print 'restoring focus'
            if widgetsOnBackWindowsCanGrabFocus is False:
                lActiveWindow = self.lastFocus.focus_get()
                if    lActiveWindow is not None \
                  and ( lActiveWindow.winfo_toplevel() != self.lastFocus.winfo_toplevel() ):
                    return

            self.lastFocus.focus_set()
            self.lastFocus = None
            event.widget.config(cursor='')

    def enter_cb(self, event=None):
        # make sure widget gets keyboard events
        #print 'enter', event.widget

        if widgetsOnBackWindowsCanGrabFocus is False:
            lActiveWindow = event.widget.focus_get()
            if    lActiveWindow is not None \
              and ( lActiveWindow.winfo_toplevel() != event.widget.winfo_toplevel() ):
                return

        if self.lastFocus is None:
            #print 'setting focus'
            self.lastFocus = self.focus_lastfor()
        event.widget.focus_set()
        event.widget.config(cursor='xterm')

    def return_cb(self, event):
        # return should destroy the topEntry
        #print "return_cb"
        if self.typedValueTK is not None:
            self.typedValueTK.destroy()
        if self.topEntry is not None:
            self.topEntry.destroy()
        self.topEntry = None
        if len(self.typedValue):
            #print 'setting to', self.type(self.typedValue)
            self.callSet(self.typedValue)
        self.typedValue = ''

    ## TO BE SUBCLASSED

    def handleKeyStroke(self, event):
        # by default we handle delete character keys
        key = event.keysym
        if key == 'BackSpace' or key == 'Delete':
            self.typedValue = self.typedValue[:-1]
            self.typedValueTK.configure(text=self.typedValue)
Exemplo n.º 44
0
    def help_about(self):

        """Shows an 'about' modal dialog.

        Callback method called by tk.

        """

        about_win = Toplevel(self.root)

        # Set up dialog

        lbl = Label(about_win, text="Video Poker")
        lbl.grid(row=0, column=0, padx=10, pady=(10, 0), sticky=W + N)
        lbl = Label(about_win, text="by Paul Griffiths")
        lbl.grid(row=1, column=0, padx=10, pady=(0, 7), sticky=W + N)
        lbl = Label(about_win, text="Written in Python, with tkinter.")
        lbl.grid(row=2, column=0, padx=10, pady=7, sticky=W + N)
        lbl = Label(about_win, text="Copyright 2013 Paul Griffiths")
        lbl.grid(row=4, column=0, padx=10, pady=(7, 0), sticky=W + N)
        lbl = Label(about_win, text="Email: [email protected]")
        lbl.grid(row=5, column=0, padx=10, pady=(0, 21), sticky=W + N)
        lbl = Label(about_win, text="This program is free software: you can " +
            "redistribute it and/or modify it under the terms")
        lbl.grid(row=6, column=0, columnspan=2,
                 padx=10, pady=0, sticky=W + N)
        lbl = Label(about_win, text="of the GNU General Public License as " +
            "published by the Free Software Foundation, either")
        lbl.grid(row=7, column=0, columnspan=2,
                 padx=10, pady=(0, 0), sticky=W + N)
        lbl = Label(about_win, text="version 3 of the License, or " +
            "(at your option) any later version.")
        lbl.grid(row=8, column=0, columnspan=2,
                 padx=10, pady=(0, 21), sticky=W + N)
        lbl = Label(about_win, text="This program is distributed in " +
            "the hope that it will be useful, but WITHOUT ANY WARRANTY;")
        lbl.grid(row=9, column=0, columnspan=2,
                 padx=10, pady=0, sticky=W + N)
        lbl = Label(about_win, text="without even the implied " +
            "warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR")
        lbl.grid(row=10, column=0, columnspan=2,
                 padx=10, pady=(0, 0), sticky=W + N)
        lbl = Label(about_win, text="PURPOSE. See the " +
            "GNU General Public License for more details.")
        lbl.grid(row=11, column=0, columnspan=2,
                 padx=10, pady=(0, 21), sticky=W + N)
        lbl = Label(about_win, text="You should have received a " +
            "copy of the GNU General Public License along with this")
        lbl.grid(row=12, column=0, columnspan=2,
                 padx=10, pady=(0, 0), sticky=W + N)
        lbl = Label(about_win, text="program. If not, see " +
            "<http://www.gnu.org/licenses/>.")
        lbl.grid(row=13, column=0, columnspan=2,
                 padx=10, pady=(0, 21), sticky=W + N)
        img = PhotoImage(file="{0}27.gif".format(self.gifdir))
        lbl = Label(about_win, image=img)
        lbl.grid(row=0, column=1, rowspan=5, padx=10, pady=10, sticky=N + E)

        btn = Button(about_win, text="OK", command=about_win.quit)
        btn.grid(row=14, column=0, columnspan=2,
                 padx=0, pady=(0, 10), ipadx=30, ipady=3)

        # Show dialog

        about_win.transient(self.root)
        about_win.parent = self.root
        about_win.protocol("WM_DELETE_WINDOW", about_win.destroy)
        about_win.geometry("+{0}+{1}".format(self.root.winfo_rootx() + 50,
                                           self.root.winfo_rooty() + 50))
        about_win.title("About Video Poker")
        about_win.focus_set()
        about_win.grab_set()
        about_win.mainloop()
        about_win.destroy()
Exemplo n.º 45
0
class ui:
    def __init__(self, r):
        self.__root = r         # root of program
        self.__load_icon = ImageTk.PhotoImage(file=constants.PATH + r'/ico/load.png')

        self.__master_file = ""         # file to merge into
        self.__convert_list = []        # holds list of files to be converted
        self.__sub_list = []            # holds list of files to compare against master

        self.__convert_opts = None      # Top level for additional convert options
        self.__nth_number = None        # Entry box for holding nth number for convert option
        self.__lbl_file = None          # Label which holds name of master file in top left corner
        self.__convert_lbox = None      # Listbox for holding list of files to convert
        self.__sub_lbox = None          # Listbox for holding list of files to compare against master file

        self.__match_rule = IntVar()        # the rule on how to merge files into master
        self.__column_rule = IntVar()       # which column to use for comparing
        self.__column_rule.set(1)           # initial value is the first column
        self.__column_match_rule = IntVar() # which column to compare for a match
        self.__column_match_rule.set(1)     # initial value is the first column

        # public window dimensions
        self.width = self.__root.winfo_screenwidth()
        self.height = self.__root.winfo_screenheight()

        # upper left side of screen
        self.__master_frame = Frame(self.__root, width=constants.WIDTH/3, borderwidth=1, relief=SOLID,
                                    height=constants.HEIGHT/4)
        self.__master_frame.grid_propagate(False)
        self.__master_frame.grid(row=0, column=0, padx=5, pady=5)

        # lower left side of screen
        self.__convert_frame = Frame(self.__root, width=constants.WIDTH/3, borderwidth=1, relief=SOLID,
                                     height=constants.HEIGHT - constants.HEIGHT/4 - 20)
        self.__convert_frame.pack_propagate(False)
        self.__convert_frame.grid(row=1, column=0, padx=5, pady=5)

        # right side of screen
        self.__sub_frame = Frame(self.__root, width=constants.WIDTH - constants.WIDTH/3 - 20, borderwidth=1, relief=SOLID,
                                 height=constants.HEIGHT - 10)
        self.__sub_frame.grid_propagate(False)
        self.__sub_frame.grid(row=0, column=1, padx=5, pady=5, columnspan=2, rowspan=2)

    def setup_gui(self):
        """
        Top level function which is called from main(). Sets window title and dimensions, then calls three sub
        routines which created and setup the rest of the GUI
        """
        self.__root.title('db_swapper')
        x = (self.width - constants.WIDTH) / 2
        y = (self.height - constants.HEIGHT) / 2

        self.__root.geometry('%dx%d+%d+%d' % (constants.WIDTH, constants.HEIGHT, x, y))

        self.create_master_frame()
        self.create_convert_frame()
        self.create_sub_frame()

    def create_master_frame(self):
        """
        Initialize the GUI for the upper left
        """
        load_btn = Button(self.__master_frame, image=self.__load_icon, width=20, height=20,
                          command=self.import_master_file)
        load_btn.grid(row=1, column=1, padx=5, pady=5)

        Label(self.__master_frame, text="Master List").\
            grid(row=1, column=2, padx=5, pady=5)

        self.__lbl_file = Label(self.__master_frame, bg="white", relief=SUNKEN, width=26)
        self.__lbl_file.grid(row=2, column=1, padx=5, pady=5, columnspan=3)

        # adding these weights allows the GUI to align itself within the frame
        self.__master_frame.grid_rowconfigure(0, weight=1)
        self.__master_frame.grid_columnconfigure(3, weight=1)
        self.__master_frame.grid_rowconfigure(3, weight=1)
        self.__master_frame.grid_columnconfigure(0, weight=1)

    def create_convert_frame(self):
        """
        Initialize the GUI for the lower left side of the program
        """
        Label(self.__convert_frame, text="Files to split").\
            pack(side=TOP)

        self.__convert_lbox = Listbox(self.__convert_frame, width=29, height=12, selectmode=EXTENDED)
        self.__convert_lbox.pack(side=TOP)

        convert = Button(self.__convert_frame, text="Convert", command=self.choose_convert)
        remove = Button(self.__convert_frame, text="Remove Item",
                        command=lambda: self.remove_item(self.__convert_lbox, self.__convert_list))
        load = Button(self.__convert_frame, image=self.__load_icon, width=27, height=20,
                      command=lambda: self.import_and_append_file(self.__convert_lbox, self.__convert_list))

        convert.pack(side=LEFT, padx=(10,5), pady=5)
        remove.pack(side=LEFT, padx=(0,5))
        load.pack(side=LEFT)

    def create_sub_frame(self):
        """
        Initialize the GUI for the right side of the program
        """
        self.__sub_lbox = Listbox(self.__sub_frame, width = 30, height = 23, selectmode=EXTENDED)
        self.__sub_lbox.grid(row=0, column=0, rowspan=20, padx=5, pady=5)

        Label(self.__sub_frame, justify=LEFT,
                    text = "To use db_swapper first load a\nmaster list, the database you wish\nto"
                           " merge files into. Then add\nany sub files to compare against\nand hit"
                           " 'merge'. Use convert to\nsplit a large file into smaller files\n"
                           "using the popup options").\
            grid(row=1, column=1, rowspan=20, columnspan=4, sticky=N+W)

        Label(self.__sub_frame, text="Merge into master if a matched\nsub item is:", justify=LEFT).\
            grid(row=11, column=1, sticky=W, rowspan=3, columnspan=4)

        Radiobutton(self.__sub_frame, text="Less", variable=self.__match_rule, value=constants.LESS).\
            grid(row=14, column=1, sticky=W)
        Radiobutton(self.__sub_frame, text="Greater", variable=self.__match_rule, value=constants.GREATER).\
            grid(row=14, column=2, sticky=W)
        Radiobutton(self.__sub_frame, text="Equal", variable=self.__match_rule, value=constants.EQUAL).\
            grid(row=14, column=3, sticky=W)

        Label(self.__sub_frame, text="Column to match with:", justify=LEFT).\
            grid(row=15, column=1, sticky=W, columnspan=4)

        OptionMenu(self.__sub_frame, self.__column_match_rule,1,2,3,4,5,6,7,8,9,10).\
            grid(row=15, column=3, sticky=E)

        Label(self.__sub_frame, text="Column to compare to:", justify=LEFT).\
            grid(row=16, column=1, sticky=W, columnspan=4)

        OptionMenu(self.__sub_frame, self.__column_rule,1,2,3,4,5,6,7,8,9,10).\
            grid(row=16,column=3,sticky=E)

        # Merge button
        Button(self.__sub_frame, text="Merge", width=24, command=self.merge_files).\
            grid(row=19, column=1, padx=(0,5), columnspan=4, sticky=W)

        # Load button for merge frame
        Button(self.__sub_frame, image=self.__load_icon, width=73, height=35,
                      command=lambda: self.import_and_append_file(self.__sub_lbox, self.__sub_list)).\
            grid(row=18, column=1, padx=(0,0), sticky=W, columnspan=2)

        # Remove button for merge frame
        Button(self.__sub_frame, text="Remove Item", width=10, height=2,
                        command=lambda: self.remove_item(self.__sub_lbox, self.__sub_list)).\
            grid(row=18, column=2, padx=(40,0), sticky=W, columnspan=2)

    def choose_convert(self):
        """
        Creates a window that prompts the user for what type of file conversion to use. The user may
        either elect to split a file based upon it's matching first column, or split a file based
        on every Nth item, which is entered in this window.
        """
        self.__convert_opts = Toplevel()
        self.__convert_opts.title("Conversion method")

        # hard coded dimensions
        x = (self.width - 250) / 2
        y = (self.height - 100) / 2
        self.__convert_opts.geometry('%dx%d+%d+%d' % (250, 100, x, y))

        Label(self.__convert_opts, text="Which method to split by?").grid(row=0, column=0, columnspan=4)

        Button(self.__convert_opts, text="First Column", command=self.convert_files).\
            grid(row=1, column=0, sticky=W, padx=5, pady=5)
        Button(self.__convert_opts, text="By every Nth Entry", command=self.convert_files_nth).\
            grid(row=2, column=0, sticky=W, padx=5)
        self.__nth_number = Entry(self.__convert_opts)
        self.__nth_number.grid(row=2,column=1)


    def import_master_file(self):
        """
        Method called with the user chooses to import a master file, opens a dialog for the user to browse and
        select a file, then displays the file chosen within a label and sets the internal variable __master_file
        """
        file_types = [('Semicolon Separated Text Files', ('*.csv', '*.txt')), ('All Files', '*')]
        dlg = tkFileDialog.Open(filetypes=file_types)
        fl = dlg.show()
        if fl != '':
            self.__master_file = fl
            segments = self.__master_file.rpartition('/')
            self.__lbl_file.config(text=segments[2])

    def import_and_append_file(self, lbox, lbox_list):
        """
        Method to prompt a user for a selection of files, and append those files to a list box and internal list.
        Takes a Listbox and list object, and inserts the selected filenames into the Listbox and the full path
        filenames into the list
        """
        file_types = [('Semicolon Separated Files', ('*.csv', '*.txt')), ('All Files', '*')]
        files = list(tkFileDialog.askopenfilenames(filetypes=file_types))
        if files is not None:
            for file in files:
                lbox.insert(END, file.rpartition('/')[2])
                lbox_list.append(file)

    def remove_item(self, lbox, lbox_list):
        """
        Removes any items currently selected in a listbox passed. Also ensures to remove that item from the internal
        list passed.
        """
        indexes = list(lbox.curselection())

        # Remove in reversed order so the indices do not change as we delete
        for idx in reversed(indexes):
            lbox.delete(idx)
            del lbox_list[idx]

    def convert_files(self):
        """
        Splits a large csv file into smaller csv files based upon their first column
        """
        logger.info('Converting file(s) based upon first column')
        self.__convert_opts.destroy()

        if not self.__convert_list:
            logger.error('No files to convert')
            return

        # loop through each file in the Listbox
        for item in self.__convert_list:
            with open(item, 'rb') as file:
                # open the file and create a reader
                master_reader = csv.reader(file, delimiter=constants.DELIMITER)
                curr = None     # keeps track of current running subject
                segment = []    # rows are appended to this list as long as the subject remains the same
                for row in master_reader:
                    # if curr is empty, start a new subject
                    if curr is None: curr = row[0]
                    if curr != row[0]:
                        # sometimes the csv file contains a header sep, if so then ignore it
                        if 'sep=' in curr:
                            curr = None
                            segment=[]
                            continue
                        # create a csv file with the name of the subject
                        with open(constants.PATH + '/' + curr + '.csv', 'wb') as write_out:
                            # write out the delimiter helper, then write the segment list
                            write_out.write('sep='+constants.DELIMITER + '\n')
                            writer = csv.writer(write_out, delimiter=constants.DELIMITER)
                            for seg in segment:
                                writer.writerow(seg)
                        segment = []
                        curr = row[0]       # if row doesn't match previous curr, it becomes the new curr
                        segment.append(row) # append this row to the start of the new curr
                    else:
                        segment.append(row)
                # if segments has data for a subject at the end of the loop, write the data to the subject
                if list is not None:
                    with open(constants.PATH + '/' + curr + '.csv', 'wb') as write_out:
                        write_out.write('sep='+constants.DELIMITER + '\n')
                        writer = csv.writer(write_out, delimiter=constants.DELIMITER)
                        for seg in segment:
                            writer.writerow(seg)

        logger.info('FINISHED, split files can be found in installation directory')

    def convert_files_nth(self):

        if not self.__convert_list:
            logger.error('No files to convert')
            return

        # if the text in the entry box cannot be converted, display error
        try:
            num = int(self.__nth_number.get())
        except:
            logger.error('Invalid number of entries given: \'%s\'' % self.__nth_number.get())
            self.__convert_opts.destroy()
            return

        self.__convert_opts.destroy()
        logger.info('Converting file(s) based upon every nth item')
        for item in self.__convert_list:
            with open(item, 'rb') as file:
                master_reader = csv.reader(file, delimiter=constants.DELIMITER)
                count = 0
                parts = 0
                segment = []
                for row in master_reader:
                    if('sep=' in '\t'.join(row)):
                        continue
                    count += 1
                    segment.append(row)
                    if(count == num):
                        with open(constants.PATH + '/%spart%d' %
                                ((item.rpartition('/')[2])[:-4], parts) + '.csv', 'wb') as write_out:
                            write_out.write('sep='+constants.DELIMITER + '\n')
                            writer = csv.writer(write_out, delimiter=constants.DELIMITER)
                            for seg in segment:
                                writer.writerow(seg)
                        segment = []
                        parts += 1
                        count = 0
            if count != 0:
                with open(constants.PATH + '/%spart%d' % ((item.rpartition('/')[2])[:-4], parts) + '.csv', 'wb') as write_out:
                    write_out.write('sep='+constants.DELIMITER + '\n')
                    writer = csv.writer(write_out, delimiter=constants.DELIMITER)
                    for seg in segment:
                        writer.writerow(seg)

        logger.info('FINISHED, split files can be found in installation directory')




    def merge_files(self):
        """
        Merges small files into a master file based upon a matching criteria. all files in __sub_list are compared
        to __master_file.
        """
        compare_col = self.__column_rule.get() - 1
        match_col = self.__column_match_rule.get() - 1
        rule = self.__match_rule.get()

        if rule == 0:
            logger.error('Rule not selected, select LESS, GREATER, or EQUAL')
            return

        if self.__master_file == "":
            logger.error('No master file selected')
            return

        if self.__sub_list is None:
            logger.error('No sub files selected')
            return

        s = ""
        if rule == constants.LESS: s = "LESS than"
        elif rule == constants.GREATER: s = "GREATER than"
        elif rule == constants.EQUAL: s = "EQUAL to"
        logger.info('beginning merge, using column #%d for finding matching rows' % match_col)
        logger.info('Checking column #%d to decide whether to overwrite rows' % compare_col)
        logger.info('overwriting will occur if child row is %s parent row' % s)

        # move master file into a list for comparing and overwriting
        master_list = []
        with open(self.__master_file, 'rb') as m_file:
            master_reader = csv.reader(m_file, delimiter=constants.DELIMITER)
            for row in master_reader:
                master_list.append(row)

        # run each sub file through the master list to swap
        changed = False
        for sub_file in self.__sub_list:
            sub_list = []
            with open(sub_file, 'rb') as file:
                sub_reader = csv.reader(file, delimiter=constants.DELIMITER)
                for sr in sub_reader:
                    sub_list.append(sr)

            row_num = 1
            non_decimal = re.compile(r'[^\d.]+')
            for row in master_list:
                for sub_row in sub_list:
                    if str(sub_row[match_col]).lower() == str(row[match_col]).lower() and \
                        (not 'sep=' in str(sub_row[match_col])):
                        ms_val = int(float(non_decimal.sub('',row[compare_col])))
                        sb_val = int(float(non_decimal.sub('',sub_row[compare_col])))
                        if rule == constants.LESS and sb_val < ms_val or \
                           rule == constants.GREATER and sb_val > ms_val or \
                           rule == constants.EQUAL and sb_val == ms_val:
                            changed = True
                            logger.info('row #%d: SWAPPING %s in master list for %s in %s' %
                                        (row_num, ','.join(row), ','.join(sub_row), sub_file.rpartition('/')[2]))
                            master_list[(row_num-1)] = sub_row
                row_num+= 1

        # write back master list into master file with new changes
        if changed:
            with open((self.__master_file.rpartition('/')[2])[:-4] + '_swapped.csv', 'wb') as m_file:
                master_writer = csv.writer(m_file, delimiter=constants.DELIMITER)
                for row in master_list:
                    master_writer.writerow(row)

        logger.info('FINISHED, swapped file located in installation directory')
Exemplo n.º 46
0
class sideWindow(AppShell):
    #################################################################
    # sideWindow(AppShell)
    # This class will open a side window wich contains a scene graph and
    # a world setting page.
    #################################################################
    appversion      = '1.0'
    appname         = 'Navigation Window'
    frameWidth      = 325
    frameHeight     = 580
    frameIniPosX    = 0
    frameIniPosY    = 110
    padx            = 0
    pady            = 0

    lightEnable = 0
    ParticleEnable = 0
    basedriveEnable = 0
    collision = 0
    backface = 0
    texture = 1
    wireframe = 0

    enableBaseUseDrive = 0

    def __init__(self, worldColor,lightEnable,ParticleEnable, basedriveEnable,collision,
                 backface, texture, wireframe, grid, widgetVis, enableAutoCamera, parent = None, nodePath = render, **kw):
        self.worldColor = worldColor
        self.lightEnable = lightEnable
        self.ParticleEnable = ParticleEnable
        self.basedriveEnable = basedriveEnable
        self.collision = collision
        self.backface = backface
        self.texture = texture
        self.wireframe = wireframe
        self.grid = grid
        self.enableAutoCamera = enableAutoCamera
        self.widgetVis = widgetVis

        # Define the megawidget options.
        optiondefs = (
            ('title',       self.appname,       None),
            )
        self.defineoptions(kw, optiondefs)

        if parent == None:
            self.parent = Toplevel()
        else:
            self.parent = parent

        AppShell.__init__(self, self.parent)
        self.parent.geometry('%dx%d+%d+%d' % (self.frameWidth, self.frameHeight,self.frameIniPosX,self.frameIniPosY))

        self.parent.resizable(False,False) ## Disable the ability to resize for this Window.

    def appInit(self):
        print '----SideWindow is Initialized!!'

    def createInterface(self):
        # The interior of the toplevel panel
        interior = self.interior()
        mainFrame = Frame(interior)
        ## Creat NoteBook
        self.notebookFrame = Pmw.NoteBook(mainFrame)
        self.notebookFrame.pack(fill=Tkinter.BOTH,expand=1)
        sgePage = self.notebookFrame.add('Tree Graph')
        envPage = self.notebookFrame.add('World Setting')
        self.notebookFrame['raisecommand'] = self.updateInfo

        ## Tree Grapgh Page
        self.SGE = seSceneGraphExplorer.seSceneGraphExplorer(
            sgePage, nodePath = render,
            scrolledCanvas_hull_width = 270,
            scrolledCanvas_hull_height = 570)
        self.SGE.pack(fill = Tkinter.BOTH, expand = 0)

        ## World Setting Page
        envPage = Frame(envPage)
        pageFrame = Frame(envPage)
        self.LightingVar = IntVar()
        self.LightingVar.set(self.lightEnable)
        self.LightingButton = Checkbutton(
            pageFrame,
            text = 'Enable Lighting',
            variable = self.LightingVar,
            command = self.toggleLights)
        self.LightingButton.pack(side=Tkinter.LEFT, expand=False)
        pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True)

        pageFrame = Frame(envPage)
        self.CollisionVar = IntVar()
        self.CollisionVar.set(self.collision)
        self.CollisionButton = Checkbutton(
            pageFrame,
            text = 'Show Collision Object',
            variable = self.CollisionVar,
            command = self.showCollision)
        self.CollisionButton.pack(side=Tkinter.LEFT, expand=False)
        pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True)

        pageFrame = Frame(envPage)
        self.ParticleVar = IntVar()
        self.ParticleVar.set(self.ParticleEnable)
        self.ParticleButton = Checkbutton(
            pageFrame,
            text = 'Show Particle Dummy',
            variable = self.ParticleVar,
            command = self.enableParticle)
        self.ParticleButton.pack(side=Tkinter.LEFT, expand=False)
        pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True)

        pageFrame = Frame(envPage)
        self.baseUseDriveVar = IntVar()
        self.baseUseDriveVar.set(self.basedriveEnable)
        self.baseUseDriveButton = Checkbutton(
            pageFrame,
            text = 'Enable base.usedrive',
            variable = self.baseUseDriveVar,
            command = self.enablebaseUseDrive)
        self.baseUseDriveButton.pack(side=Tkinter.LEFT, expand=False)
        pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True)

        pageFrame = Frame(envPage)
        self.backfaceVar = IntVar()
        self.backfaceVar.set(self.backface)
        self.backfaceButton = Checkbutton(
            pageFrame,
            text = 'Enable BackFace',
            variable = self.backfaceVar,
            command = self.toggleBackface)
        self.backfaceButton.pack(side=Tkinter.LEFT, expand=False)
        pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True)

        pageFrame = Frame(envPage)
        self.textureVar = IntVar()
        self.textureVar.set(self.texture)
        self.textureButton = Checkbutton(
            pageFrame,
            text = 'Enable Texture',
            variable = self.textureVar,
            command = self.toggleTexture)
        self.textureButton.pack(side=Tkinter.LEFT, expand=False)
        pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True)

        pageFrame = Frame(envPage)
        self.wireframeVar = IntVar()
        self.wireframeVar.set(self.wireframe)
        self.wireframeButton = Checkbutton(
            pageFrame,
            text = 'Enable Wireframe',
            variable = self.wireframeVar,
            command = self.toggleWireframe)
        self.wireframeButton.pack(side=Tkinter.LEFT, expand=False)
        pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True)

        pageFrame = Frame(envPage)
        self.gridVar = IntVar()
        self.gridVar.set(self.grid)
        self.gridButton = Checkbutton(
            pageFrame,
            text = 'Enable Grid',
            variable = self.gridVar,
            command = self.toggleGrid)
        self.gridButton.pack(side=Tkinter.LEFT, expand=False)
        pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True)

        pageFrame = Frame(envPage)
        self.widgetVisVar = IntVar()
        self.widgetVisVar.set(self.widgetVis)
        self.widgetVisButton = Checkbutton(
            pageFrame,
            text = 'Enable WidgetVisible',
            variable = self.widgetVisVar,
            command = self.togglewidgetVis)
        self.widgetVisButton.pack(side=Tkinter.LEFT, expand=False)
        pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True)

        pageFrame = Frame(envPage)
        self.enableAutoCameraVar = IntVar()
        self.enableAutoCameraVar.set(self.enableAutoCamera)
        self.enableAutoCameraButton = Checkbutton(
            pageFrame,
            text = 'Enable Auto Camera Movement for Loading Objects',
            variable = self.enableAutoCameraVar,
            command = self.toggleAutoCamera)
        self.enableAutoCameraButton.pack(side=Tkinter.LEFT, expand=False)
        pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True)

        pageFrame = Frame(envPage)
        self.backgroundColor = ColorEntry(
            pageFrame, text = 'BG Color', value=self.worldColor)
        self.backgroundColor['command'] = self.setBackgroundColorVec
        self.backgroundColor['resetValue'] = [0,0,0,0]
        self.backgroundColor.pack(side=Tkinter.LEFT, expand=False)
        self.bind(self.backgroundColor, 'Set background color')
        pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True)

        envPage.pack(expand=False)

        ## Set all stuff done
        self.notebookFrame.setnaturalsize()
        mainFrame.pack(fill = 'both', expand = 1)


    def createMenuBar(self):
        # We don't need menu bar here.
        self.menuBar.destroy()

    def onDestroy(self, event):
        #################################################################
        # onDestroy(self, event)
        # This function will be called when user closed the side window.
        # Here we will send out a message with whole data set we will need
        # for the next time user open the side window.
        #################################################################
        messenger.send('SW_close',[self.worldColor,
                                   self.lightEnable,
                                   self.ParticleEnable,
                                   self.basedriveEnable,
                                   self.collision,
                                   self.backface,
                                   self.texture,
                                   self.wireframe,
                                   self.grid,
                                   self.widgetVis,
                                   self.enableAutoCamera])
        '''
        If you have open any thing, please rewrite here!
        '''
        pass

    ###############################
    def updateInfo(self, page = 'Tree Graph'):
        #################################################################
        # updateInfo(self, page = 'Tree Graph')
        # This function will be called when each time user change the main
        # page of the window.
        # What it dose is to call right function to restore the data for current selected page.
        #################################################################
        if page=='Tree Graph':
            self.updateTreeGraph()
        elif page == 'World Setting':
            self.updateWorldSetting()

    def updateTreeGraph(self):
        #################################################################
        # updateTreeGraph(self)
        # When scene graoh page has been opend, call sceneGraphExplorer to
        # updata the tree.
        #################################################################
        self.SGE.update()
        pass

    def updateWorldSetting(self):
        #################################################################
        # updateWorldSetting(self)
        # When world setting page has been selected, this function will
        # reset those check box in the page to reflect the current world setting.
        #################################################################
        self.LightingVar.set(self.lightEnable)

        self.CollisionVar.set(self.collision)
        self.ParticleVar.set(self.ParticleEnable)
        self.baseUseDriveVar.set(self.basedriveEnable)
        self.backgroundColor.set(value = self.worldColor)
        pass

    def toggleLights(self):
        #################################################################
        # toggleLights(self)
        # send out a message to let sceneEditor know we need to toggle the light.
        # Then, sceneEditor will pass the message to dataHolder to disable/enable
        # the lights. (lightManager is inside the dataHolder)
        #################################################################
        self.lightEnable = (self.lightEnable+1)%2
        messenger.send('SW_lightToggle')
        pass

    def showCollision(self):
        #################################################################
        # showCollision(self)
        # This function will send out a message to sceneEditor to toggle
        # the visibility of collision objects.
        #################################################################
        self.collision = (self.collision+1)%2
        messenger.send('SW_collisionToggle', [self.collision])
        pass

    def enableParticle(self):
        #################################################################
        # enableParticle(self)
        # This function will send out a message to sceneEditor to toggle
        # the visibility of particle objects.
        #################################################################
        self.ParticleEnable = (self.ParticleEnable+1)%2
        messenger.send('SW_particleToggle', [self.ParticleEnable])
        pass

    def enablebaseUseDrive(self):
        #################################################################
        # enablebaseUseDrive(self)
        # This function will toggle the usage of base.useDrive.
        # Well, it may not usefull at all.
        #
        # We won't send out any message in this time to notice
        # the sceneEditor this event happend.
        # In the other hand, we will restore it back when
        # the side window has been closed.
        #
        #################################################################
        if self.enableBaseUseDrive==0:
            print 'Enabled'
            base.useDrive()
            self.enableBaseUseDrive = 1
        else:
            print 'disabled'
            #base.useTrackball()
            base.disableMouse()
            self.enableBaseUseDrive = 0
        self.basedriveEnable = (self.basedriveEnable+1)%2
        pass

    def toggleBackface(self):
        #################################################################
        # toggleBackface(self)
        # This function will toggle the back face setting. so it will
        # render the polygon with two sides.
        #################################################################
        base.toggleBackface()
        self.backface = (self.backface+1)%2
        return

    def toggleBackfaceFromMainW(self):
        #################################################################
        # toggleBackfaceFromMainW(self)
        # This function is called by sceneEditor when user used hot key
        # to toggle the back face setting in the main panda window.
        # In here we will only reset the flag and reset the state of
        # check box
        #################################################################
        self.backface = (self.backface+1)%2
        self.backfaceButton.toggle()
        return

    def toggleTexture(self):
        #################################################################
        # toggleTexture(self)
        # This function will toggle the txture using option for the whole scene.
        #################################################################
        base.toggleTexture()
        self.texture = (self.texture+1)%2
        return

    def toggleTextureFromMainW(self):
        #################################################################
        # toggleTextureFromMainW(self)
        # This function is called by sceneEditor when user used hot key
        # to toggle the texture usage from the main panda window.
        # In here we will only reset the flag and reset the state of
        # check box
        #################################################################
        self.texture = (self.texture+1)%2
        self.textureButton.toggle()
        return

    def toggleWireframe(self):
        #################################################################
        # toggleWireframe(self)
        # This function will toggle the wire frame mode.
        #################################################################
        base.toggleWireframe()
        self.wireframe = (self.wireframe+1)%2
        return

    def toggleWireframeFromMainW(self):
        #################################################################
        # toggleWireframeFromMainW(self)
        # This function is called by sceneEditor when user used hot key
        # to toggle the wire frame mode in the main panda window.
        # In here we will only reset the flag and reset the state of
        # check box
        #################################################################
        self.wireframe = (self.wireframe+1)%2
        self.wireframeButton.toggle()
        return

    def toggleGrid(self):
        #################################################################
        # toggleGrid(self)
        # This function will toggle the usage of the grid.
        #################################################################
        self.grid = (self.grid+1)%2
        if self.grid==1:
            SEditor.grid.enable()
        else:
            SEditor.grid.disable()

    def togglewidgetVis(self):
        #################################################################
        # togglewidgetVis(self)
        # This function will toggle the visibility of the widget of the grid.
        #################################################################
        self.widgetVis = (self.widgetVis+1)%2
        SEditor.toggleWidgetVis()
        if SEditor.widget.fActive:
                messenger.send('shift-f')
        return

    def toggleWidgetVisFromMainW(self):
        #################################################################
        # toggleWidgetVisFromMainW(self)
        # This function is called by sceneEditor when user used hot key
        # to toggle the visibility of widgets ('v') from the main panda window.
        # In here we will only reset the flag and reset the state of
        # check box
        #################################################################
        self.widgetVis = (self.widgetVis+1)%2
        self.widgetVisButton.toggle()
        return

    def setBackgroundColorVec(self,color):
        #################################################################
        # setBackgroundColorVec(self,color)
        # Call back function
        # This will be called from the colorEntry on the world setting page.
        # The "color" here is a list containing three integer data, R, G and B.
        #################################################################
        base.setBackgroundColor(color[0]/255.0,
                                color[1]/255.0,
                                color[2]/255.0)
        self.worldColor = [color[0],color[1],color[2],0]

    def toggleAutoCamera(self):
        #################################################################
        # toggleAutoCamera(self)
        # This function will toggle the usage of the auto-camera movement
        # when user loaded model or actor into the scene.
        #################################################################
        self.enableAutoCamera = (self.enableAutoCamera+1)%2
        SEditor.toggleAutoCamera()
        return

    def selectPage(self,page='Tree Graph'):
        #################################################################
        #################################################################
        self.notebookFrame.selectpage(page)
Exemplo n.º 47
0
class VirtualHarry:
# Support ======================================================================

    def setSVtoV(self, sv, v):
        for i in range(len(sv)):
            sv[i].set(str(v[i]))

# Make Utilities ===============================================================

    def mkConstants(self):
        self.Range = range(8)
        self.Egnar = self.Range.reverse()
        self.Range3 = range(3)
        self.Range16 = range(16)

    def mkTopFaces(self, r):
        
        self.WHOLE = Toplevel(r)
        self.WHOLE.title("Virtual Harry")
        self.WHOLE.geometry("+40+35")
        
        self.UNITY = Frame(self.WHOLE)
        self.UNITY.grid(row=0, column=0)

        self.RF = registerface(self.UNITY)       
        self.FF = functionface(self.UNITY)
        self.SF = statesface(self.UNITY)
        self.ALUF = aluface(self.UNITY)
        self.CF = controlface(self.UNITY)
        self.EF = encoderface(self.UNITY)

        self.RF.grid(row=0,column=0, columnspan=2)
        self.FF.grid(row=1,column=0)
        self.SF.grid(row=1,column=1)
        self.ALUF.grid(row=2,column=0)
        self.CF.grid(row=2,column=1)
        self.EF.grid(row=3, column=0, columnspan=2)

        self.SEQUENCERFACE = Frame(self.WHOLE)
        self.SEQUENCERFACE.grid(row=0, column=1)

        
        self.F1 = Frame(self.SEQUENCERFACE)
        self.F2 = Frame(self.SEQUENCERFACE)        
        self.F3 = Frame(self.SEQUENCERFACE)

        self.ABF = addressbusface(self.F1)
        self.IFACE = infoface(self.F1)

        self.DF = decoderface(self.F2)
        self.MF = memoryface(self.F2)
        
        self.PF = pgmsface(self.F3)
        self.DBF = databusface(self.F3)        

        self.ABF.pack(side=LEFT, padx=3)
        self.IFACE.pack(side=RIGHT, padx=3)
        self.DF.pack(side=LEFT, padx=3)
        self.MF.pack(side=RIGHT, padx=3)
        self.PF.pack(side=LEFT, padx=3)
        self.DBF.pack(side=RIGHT, padx=3)

        self.PROCF = processface(self.SEQUENCERFACE)

        self.F1.grid(row=0, column=0)
        self.F2.grid(row=1, column=0)
        self.F3.grid(row=2, column=0)

        self.PROCF.grid(row=3, column=0, columnspan=2)

# Paint Functions ==============================================================

    def paintALU(self):
        v  = self.C.getALUregisters()
        sv = self.ALUF.getALUregisters()
        for i in range(len(v)):
            self.setSVtoV(sv[i], v[i])
        r = self.C.getResult()
        R = self.ALUF.getResult()
        self.setSVtoV(R, r)

    def recolorFunction(self):
        old = self.C.getOldFunction()
        i = 4*old[0] + 2*old[1] + old[2]
        self.ALUF.tagLabels[i].config(fg="black")
        for x in self.ALUF.registerLabels[i]:
            x.config(fg="black")

        new = self.C.getFunction()
        j = 4*new[0] + 2*new[1] + new[2]
        self.ALUF.tagLabels[j].config(fg="red")
        for y in self.ALUF.registerLabels[j]:
            y.config(fg="red")
        # A pair of dictionaries in ALUF would make 
        # this considerably less of a hack. Works.

    def paintFunction(self):
        v  = self.C.getFunction()
        sv = self.FF.getFunction()
        self.setSVtoV(sv, v)
        self.recolorFunction()

    def paintStates(self):
        v = self.C.getCYZS()
        sv = self.SF.getCYZS()
        self.setSVtoV(sv, v)

    def paintDataBus(self):
        v = self.C.getDataBus()
        sv = self.DBF.getDataBus()
        self.setSVtoV(sv, v)

    def paintAddressBus(self):
        v = self.C.getAddressBus()
        sv = self.ABF.getAddressBus()
        self.setSVtoV(sv, v)

    def paintRegister(self):
        v = self.C.getRegisters()
        sv = self.RF.getRegisters()
        for i in range(len(v)):
            self.setSVtoV(sv[i], v[i])

    def paintControl(self):
        v = self.C.getControlRegisters()
        sv = self.CF.getRegisters()
        for i in range(len(v)):
            self.setSVtoV(sv[i], v[i])
        I = self.C.getInstruction()
        Iv = self.CF.getInstruction()
        self.setSVtoV(Iv, I)
        
    def paintMemory(self):
        v = self.C.MEMORY.readMemory()
        sv = self.MF.readMemory()
        self.setSVtoV(sv, v)

    def paintNoPause(self):        
        c = "red" if self.C.NOSTEP == True else "black"
        self.DF.noStepButton.config(fg=c)

    def paintClock(self):
        self.C.updateUpTime()
        self.RF.CLKface.Hsv.set(self.C.H)
        self.RF.CLKface.Msv.set(self.C.M)
        self.RF.CLKface.Ssv.set(self.C.S)

    def paintText(self, t):
        self.PROCF.addText(t)
        sleep(0.2)

    def paintALL(self):
        self.paintALU()
        self.paintFunction()
        self.paintStates()
        self.paintDataBus()
        self.paintAddressBus()
        self.paintRegister()
        self.paintControl()
        self.paintMemory()
        self.paintNoPause()

# Make Buttons =================================================================

    def mkFunctionButtons(self):
        fb = self.FF.FUNCTIONbuttons
        for x in range(len(fb)):
            c = lambda i = x : self.C.updateFunction(i)
            fb[x].config(command = c)

    def mkDataBusButtons(self):
        db = self.DBF.DBbuttons
        for x in range(len(db)):
            c = lambda i = x : self.C.updateDataBus(i)
            db[x].config(command = c)

    def mkAddressBusButtons(self):
        ab = self.ABF.ABbuttons
        for x in range(len(ab)):
            c = lambda i = x : self.C.updateAddressBus(i)
            ab[x].config(command = c)

# Load Buttons =================================================================

    def mkLoadButtons(self):
        self.RF.AloadButton.config(command  = self.C.loadA)
        self.RF.BloadButton.config(command  = self.C.loadB)
        self.RF.CloadButton.config(command  = self.C.loadC)
        self.RF.DloadButton.config(command  = self.C.loadD)
        self.RF.M1loadButton.config(command = self.C.loadM1)
        self.RF.M2loadButton.config(command = self.C.loadM2)
        self.RF.XloadButton.config(command  = self.C.loadX)
        self.RF.YloadButton.config(command  = self.C.loadY)
        self.RF.XYloadButton.config(command = self.C.loadXY)
        
        self.CF.J1loadButton.config(command   = self.C.loadJ1)
        self.CF.J2loadButton.config(command   = self.C.loadJ2)        
        self.CF.INSTloadButton.config(command = self.C.loadInst)
        self.CF.INCloadButton.config(command  = self.C.loadINC)
        self.CF.PCloadButton.config(command   = self.C.loadPC)

        self.MF.READ.config(command = self.C.memRead)

# Select Buttons ===============================================================

    def mkSelectButtons(self):
        self.ALUF.LOADbutton.config(command = self.C.selectResult)
        self.RF.AselectButton.config(command = self.C.selectA)
        self.RF.BselectButton.config(command = self.C.selectB)
        self.RF.CselectButton.config(command = self.C.selectC)
        self.RF.DselectButton.config(command = self.C.selectD)        
        self.RF.M1selectButton.config(command = self.C.selectM1)
        self.RF.M2selectButton.config(command = self.C.selectM2)
        self.RF.XselectButton.config(command = self.C.selectX)
        self.RF.YselectButton.config(command = self.C.selectY)        
        self.RF.MselectButton.config(command = self.C.selectM)
        self.RF.XYselectButton.config(command = self.C.selectXY)

        self.CF.JselectButton.config(command = self.C.selectJ)
        self.CF.PCselectButton.config(command = self.C.selectPC)
        self.CF.INCselectButton.config(command = self.C.selectINC)

        self.MF.WRITE.config(command = self.C.memWrite)

# Run Buttons ==================================================================

    def loadREADME(self):
        readmefile = open("README", "r")
        for LINE in readmefile:
            self.PROCF.addText(LINE[0:len(LINE) - 1])
            #print LINE[0:len(LINE) - 1]
        readmefile.close()

    def loadPGM(self):
            PGM = []

            filename = self.PF.getPGMfileName()
            pgmFile = open(filename, 'r')

            for LINE in pgmFile:
                LINE = LINE.split()
                Address = [ int(i) for i in LINE[0]]
                Instruction = [ int(i) for i in LINE[1]]
                PGM.append([Address, Instruction])

            pgmFile.close()

            self.C.loadPGM(PGM)

    def mkRunButtons(self):
        self.DF.runButton.config(command = self.C.run)
        self.DF.stepButton.config(command = self.C.step)
        self.DF.noStepButton.config(command = self.C.noStep)

        self.PF.loadPGMbutton.config(command = self.loadPGM)

        self.MF.CLEAR.config(command = self.C.memClear)
        self.MF.RANDOM.config(command = self.C.memRandom)

        self.EF.codeButton.config(command = self.parse)

        self.IFACE.readmeButton.config(command=self.loadREADME)

# Run Buttons ==================================================================

    def parse(self):
        I = self.EF.INSTRUCTION.get()
        self.C.ENCODER.setCode(I)
        self.C.ENCODER.parse()

        #if self.C.ENCODER.evaluation == True:
        #    self.paintText( str(self.C.ENCODER.INSTRUCTION) )
            #self.EF.machinecode.set(str(self.C.ENCODER.INSTRUCTION))
        #else:
        #    self.paintText("*** Invalid Code ***")
            #self.EF.machinecode.set("> INVALID <")

# Initialization ===============================================================

    def __init__(self):
        self.mkConstants()

        self.C = core(self.paintALL)

        self.VH = Tk()
        self.VH.withdraw()

        self.mkTopFaces(self.VH)
        self.mkFunctionButtons()
        self.mkDataBusButtons()
        self.mkAddressBusButtons()
        self.mkLoadButtons()
        self.mkSelectButtons()
        self.mkRunButtons()        
        self.paintALL()
        
        self.C.setClockCallback(self.paintClock)
        self.C.runClockThread()

        self.C.setTextCallback(self.paintText)
        self.C.ENCODER.setTextCallback(self.paintText)

        self.VH.mainloop()
Exemplo n.º 48
0
class Tooltips:
	tooltip_delay = 100

	def __init__(self):
		self.descriptions = {}
		self.balloon = None
		self.balloon_label = None
		self.last_widget = ''
		self.after_id = None
		self.root = None

	def AddDescription(self, widget, description):
		self.descriptions[widget._w] = description
		if widget._w == self.last_widget:
			self.balloon_label['text'] = description

	def RemoveDescription(self, widget):
		if type(widget) == InstanceType:
			widget = widget._w
		if self.descriptions.has_key(widget):
			del self.descriptions[widget]

	def GetDescription(self, widget):
		if type(widget) == InstanceType:
			widget = widget._w
		if self.descriptions.has_key(widget):
			return self.descriptions[widget]
		return ''


	def create_balloon(self, root):
		self.root = root
		self.balloon = Toplevel(self.root)
		self.balloon.withdraw()
		self.balloon.overrideredirect(1)
		self.balloon["relief"] = 'flat'
		label = TLabel(self.balloon, text='Tooltip', style='Tooltips')
		label.pack(ipadx=2, ipady=2)
		self.balloon_label = label


	def popup_balloon(self, widget_name, x, y, text):
		self.last_widget = widget_name
		self.balloon.withdraw()
		self.balloon_label['text'] = text

		width = self.balloon_label.winfo_reqwidth()
		height = self.balloon_label.winfo_reqheight()

		screenwidth = self.root.winfo_screenwidth()
		screenheight = self.root.winfo_screenheight()

		x = self.root.winfo_pointerx()
		y = self.root.winfo_pointery() + 20

		if screenwidth < (x + width):
			x = x - width

		if screenheight < (y + height):
			y = y - height - 25

		self.balloon.geometry('%+d%+d' % (x, y))
		self.balloon.update()
		self.balloon.deiconify()
		self.balloon.tkraise()

	def popup_delayed(self, widget_name, x, y, text, *args):
		self.after_id = None
		self.popup_balloon(widget_name, x, y, text)

	def enter_widget(self, event):
		widget_name = event.widget
		text = self.GetDescription(widget_name)
		if text:
			x = event.x;y = event.y
			if self.after_id:
				print 'after_id in enter'
				self.root.after_cancel(self.after_id)
			self.after_id = self.root.after(self.tooltip_delay, self.popup_delayed, widget_name, x, y, text)

	def leave_widget(self, event):
		global last_widget, after_id
		if self.after_id is not None:
			self.root.after_cancel(self.after_id)
			self.after_id = None
			self.last_widget = ''
		last_widget = ''
		self.balloon.withdraw()

	button_press = leave_widget


	def destroy_widget(self, event):
		self.RemoveDescription(event.widget)
Exemplo n.º 49
0
class Tooltips:

    def __init__(self):
	self.descriptions = {}
	self.balloon = None
	self.balloon_label = None
	self.last_widget = ''
	self.after_id = None

    def AddDescription(self, widget, description):
	self.descriptions[widget._w] = description
	if widget._w == self.last_widget:
	    self.balloon_label['text'] = description

    def RemoveDescription(self, widget):
	if type(widget) == InstanceType:
	    widget = widget._w
	if self.descriptions.has_key(widget):
	    del self.descriptions[widget]

    def GetDescription(self, widget):
	if type(widget) == InstanceType:
	    widget = widget._w
	if self.descriptions.has_key(widget):
	    return self.descriptions[widget]
	return ''


    def create_balloon(self, root):
	self.root = root
	self.balloon = Toplevel(self.root, name = 'tooltips')
	self.balloon.withdraw()
	self.balloon.overrideredirect(1)
	label = Label(self.balloon, name = 'label', text = 'Tooltip')
	label.pack()
	self.balloon_label = label


    def popup_balloon(self, widget_name, x, y, text):
	self.last_widget = widget_name
	self.balloon.withdraw()
	self.balloon_label['text'] = text
	x = x - self.balloon_label.winfo_reqwidth() / 2
	self.balloon.geometry('%+d%+d' % (x, y))
	self.balloon.update()
	self.balloon.deiconify()
	self.balloon.tkraise()

    def popup_delayed(self, widget_name, x, y, text, *args):
	self.after_id = None
	self.popup_balloon(widget_name, x, y, text)

    def enter_widget(self, widget_name):
	text = self.GetDescription(widget_name)
	if text:
	    widget = self.root.nametowidget(widget_name)
	    x = widget.winfo_rootx() + widget.winfo_width() / 2
	    y = widget.winfo_rooty() + widget.winfo_height()
	    #y = y + height
	    #x = x + width / 2
	    if self.after_id:
		print 'after_id in enter'
		self.root.after_cancel(self.after_id)
	    self.after_id = self.root.after(config.preferences.tooltip_delay,
					    self.popup_delayed,
					    widget_name, x, y, text)

    def leave_widget(self, widget_name):
	global last_widget, after_id
	if self.after_id is not None:
	    self.root.after_cancel(self.after_id)
	    self.after_id = None
	    self.last_widget = ''
	last_widget = ''
	self.balloon.withdraw()

    button_press = leave_widget


    def destroy_widget(self, event):
	self.RemoveDescription(event.widget)
Exemplo n.º 50
0
class ContinuousTMPViewer(object):
    def __init__(self,
                 suction_height,
                 regions,
                 tl_x=0,
                 tl_y=0,
                 width=500,
                 height=150,
                 title='Grid',
                 background='tan'):
        self.tk = Tk()
        # tk.geometry('%dx%d+%d+%d'%(width, height, 100, 0))
        self.tk.withdraw()
        self.top = Toplevel(self.tk)
        self.top.wm_title(title)
        self.top.protocol('WM_DELETE_WINDOW', self.top.destroy)

        self.suction_height = suction_height
        self.regions = regions
        self.tl_x = tl_x
        self.tl_y = tl_y
        self.width = width
        self.height = height
        self.canvas = Canvas(self.top,
                             width=self.width,
                             height=self.height,
                             background=background)
        self.canvas.pack()
        # self.center()
        self.move_frame(self.tl_x, self.tl_y)

        max_width = max(
            map(get_width,
                regions.values()))  # Really should take width of max minus min
        self.dist_to_pixel = (self.width - 2 * PIXEL_BUFFER
                              ) / max_width  # Maintains aspect ratio
        self.dist_width = self.width / self.dist_to_pixel
        self.dist_height = self.height / self.dist_to_pixel
        self.ground_height = self.height - self.dist_to_pixel * ENV_HEIGHT
        self.robot_dist = self.dist_height / 2.

        self.robot = []
        self.blocks = []
        self.holding = None
        self.environment = []
        self.draw_environment()

    def center(self):
        self.top.update_idletasks()
        w = self.top.winfo_screenwidth()
        h = self.top.winfo_screenheight()
        size = tuple(
            int(_) for _ in self.top.geometry().split('+')[0].split('x'))
        x = w / 2 - size[0] / 2
        y = h / 2 - size[1] / 2
        self.top.geometry("%dx%d+%d+%d" % (size + (x, y)))

    def move_frame(self, x, y):
        self.top.update_idletasks()
        size = tuple(
            int(_) for _ in self.top.geometry().split('+')[0].split('x'))
        self.top.geometry("%dx%d+%d+%d" % (size + (x, y)))

    def scale_x(self, x):  # x \in [-self.dist_width/2, self.dist_width/2]
        return self.dist_to_pixel * (x + self.dist_width / 2.)

    def scale_y(self, y):  # y \in [0, self.dist_height]
        return self.ground_height - self.dist_to_pixel * y

    def draw_block(self, x, y, width, height, name='', color='blue'):
        self.blocks.extend([
            self.canvas.create_rectangle(self.scale_x(x - width / 2.),
                                         self.scale_y(y),
                                         self.scale_x(x + width / 2.),
                                         self.scale_y(y + height),
                                         fill=color,
                                         outline='black',
                                         width=2),
            self.canvas.create_text(self.scale_x(x),
                                    self.scale_y(y + height / 2),
                                    text=name),
        ])

    # def draw_holding(self, x, width, height, color='blue'):
    #     self.holding = self.canvas.create_rectangle(self.scale_x(x - width / 2.),
    #                                                 self.scale_y(self.robot_dist - SUCTION_HEIGHT / 2 - height),
    #                                                 self.scale_x(x + width / 2.),
    #                                                 self.scale_y(self.robot_dist - SUCTION_HEIGHT / 2),
    #                                                 fill=color, outline='black', width=2)

    def draw_region(self, region, name='', color='red'):
        x1, x2 = map(self.scale_x, region)
        y1, y2 = self.ground_height, self.height
        self.environment.extend([
            self.canvas.create_rectangle(x1,
                                         y1,
                                         x2,
                                         y2,
                                         fill=color,
                                         outline='black',
                                         width=2),
            self.canvas.create_text((x1 + x2) / 2, (y1 + y2) / 2, text=name),
        ])

    def draw_environment(self):
        # TODO: automatically draw in order
        self.environment = []
        for name, region in sorted(self.regions.items(),
                                   key=lambda pair: get_width(pair[1]),
                                   reverse=True):
            self.draw_region(region, name=name, color=name)

    def draw_robot(
        self,
        x,
        y,
        color='yellow'
    ):  # TODO - could also visualize as top grasps instead of side grasps
        #y = self.robot_dist
        self.robot = [
            self.canvas.create_rectangle(
                self.scale_x(x - SUCTION_WIDTH / 2.),
                self.scale_y(y - self.suction_height / 2.),
                self.scale_x(x + SUCTION_WIDTH / 2.),
                self.scale_y(y + self.suction_height / 2.),
                fill=color,
                outline='black',
                width=2),
            self.canvas.create_rectangle(
                self.scale_x(x - STEM_WIDTH / 2.),
                self.scale_y(y + self.suction_height / 2.),
                self.scale_x(x + STEM_WIDTH / 2.),
                self.scale_y(y + self.suction_height / 2. + STEM_HEIGHT),
                fill=color,
                outline='black',
                width=2),
        ]

    def clear_state(self):
        for block in self.blocks:
            self.canvas.delete(block)
        for part in self.robot:
            self.canvas.delete(part)
        if self.holding is not None:
            self.canvas.delete(self.holding)

    def clear_all(self):
        self.canvas.delete('all')

    def save(self, filename):
        # TODO: screen recording based on location like I did before
        # TODO: only works on windows
        # self.canvas.postscript(file='%s.ps'%filename, colormode='color')
        #from PIL import ImageGrab
        try:
            import pyscreenshot as ImageGrab
        except ImportError:
            return None
        x, y = self.top.winfo_x(), 2 * self.top.winfo_y()
        width, height = self.top.winfo_width(), self.top.winfo_height(
        )  # winfo_width, winfo_reqheight
        path = filename + '.png'
        ImageGrab.grab((x, y, x + width, y + height)).save(path)
        return path
Exemplo n.º 51
0
class Tooltips:
    tooltip_delay = 100

    def __init__(self):
        self.descriptions = {}
        self.balloon = None
        self.balloon_label = None
        self.last_widget = ''
        self.after_id = None
        self.root = None

    def AddDescription(self, widget, description):
        self.descriptions[widget._w] = description
        if widget._w == self.last_widget:
            self.balloon_label['text'] = description

    def RemoveDescription(self, widget):
        if type(widget) == InstanceType:
            widget = widget._w
        if self.descriptions.has_key(widget):
            del self.descriptions[widget]

    def GetDescription(self, widget):
        if type(widget) == InstanceType:
            widget = widget._w
        if self.descriptions.has_key(widget):
            return self.descriptions[widget]
        return ''

    def create_balloon(self, root):
        self.root = root
        self.balloon = Toplevel(self.root)
        self.balloon.withdraw()
        self.balloon.overrideredirect(1)
        self.balloon["relief"] = 'flat'
        label = TLabel(self.balloon, text='Tooltip', style='Tooltips')
        label.pack(ipadx=2, ipady=2)
        self.balloon_label = label

    def popup_balloon(self, widget_name, x, y, text):
        self.last_widget = widget_name
        self.balloon.withdraw()
        self.balloon_label['text'] = text

        width = self.balloon_label.winfo_reqwidth()
        height = self.balloon_label.winfo_reqheight()

        screenwidth = self.root.winfo_screenwidth()
        screenheight = self.root.winfo_screenheight()

        x = self.root.winfo_pointerx()
        y = self.root.winfo_pointery() + 20

        if screenwidth < (x + width):
            x = x - width

        if screenheight < (y + height):
            y = y - height - 25

        self.balloon.geometry('%+d%+d' % (x, y))
        self.balloon.update()
        self.balloon.deiconify()
        self.balloon.tkraise()

    def popup_delayed(self, widget_name, x, y, text, *args):
        self.after_id = None
        self.popup_balloon(widget_name, x, y, text)

    def enter_widget(self, event):
        widget_name = event.widget
        text = self.GetDescription(widget_name)
        if text:
            x = event.x
            y = event.y
            if self.after_id:
                print 'after_id in enter'
                self.root.after_cancel(self.after_id)
            self.after_id = self.root.after(self.tooltip_delay,
                                            self.popup_delayed, widget_name, x,
                                            y, text)

    def leave_widget(self, event):
        global last_widget, after_id
        if self.after_id is not None:
            self.root.after_cancel(self.after_id)
            self.after_id = None
            self.last_widget = ''
        last_widget = ''
        self.balloon.withdraw()

    button_press = leave_widget

    def destroy_widget(self, event):
        self.RemoveDescription(event.widget)
Exemplo n.º 52
0
class Gui(object):
    def __init__(self):

        self.root = Tk()
        self.root.title('Overwatch Replay Analyzer')
        self.root.geometry('500x300+400+200')

        self.read_path = None
        self.save_path = None
        self.left_frame = None
        self.right_frame = None
        # path
        self.create_path()
        # player
        self.create_player()
        # run
        self.run_btn = Button(self.root, text="Analyze", command=self.run)
        self.run_btn.pack()
        self.create_text()
        # check for update
        self.t = threading.Thread(target=self.check_update)
        self.t.start()

    def create_path(self):
        width_msg = 100
        width_path = 400

        path_frame = Frame(self.root)
        path_frame.pack(fill=X)
        # read
        read_frame = Frame(path_frame)
        read_frame.pack(fill=X)
        read_msg = Message(read_frame, width=width_msg, text='Video path:')
        read_msg.pack(side=LEFT)
        read_path = Message(read_frame, width=width_path, text='file1')
        read_path.pack(side=LEFT)
        read_btn = Button(read_frame,
                          text="Choose file",
                          command=self.click_read)
        read_btn.pack(side=RIGHT)
        # save
        save_frame = Frame(path_frame)
        save_frame.pack(fill=X)
        save_msg = Message(save_frame, width=width_msg, text='Save to:')
        save_msg.pack(side=LEFT)
        save_path = Message(save_frame, width=width_path, text='file2')
        save_path.pack(side=LEFT)
        save_btn = Button(save_frame,
                          text="Choose file",
                          command=self.click_save)
        save_btn.pack(side=RIGHT)

        self.read_path = read_path
        self.save_path = save_path

    def create_player(self):
        player = Frame(self.root)
        player.pack(fill=X, expand=1)
        # left
        left_frame = Frame(player)
        left_frame.pack(side=LEFT)
        left_team_name = Entry(left_frame, bg='pink', fg='black')
        left_team_name.insert(0, 'Team A')
        left_team_name.pack()
        for i in range(1, 7):
            e = Entry(left_frame, bg='red', fg='white')
            name = 'Player' + str(i)
            e.insert(0, name)
            e.pack()
        # right
        right_frame = Frame(player)
        right_frame.pack(side=RIGHT)
        right_team_name = Entry(right_frame, bg='lightBlue', fg='black')
        right_team_name.insert(0, 'Team B')
        right_team_name.pack()
        for i in range(7, 13):
            e = Entry(right_frame, bg='blue', fg='white')
            name = 'Player' + str(i)
            e.insert(0, name)
            e.pack()

        self.left_frame = left_frame
        self.right_frame = right_frame

    def create_text(self):
        self.notice_window = Toplevel(self.root)
        self.notice_window.title('Notice')
        self.notice_window.geometry('400x400+300+100')
        self.notice = Text(self.notice_window)
        self.notice.insert(
            Tkinter.INSERT,
            """Overwatch Replay Analyzer, a data extractor of Overwatch game replays

Copyright (C) 2017-2018 ORA developers

This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 3.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program.  If not, see <https://www.gnu.org/licenses/>.

You can contact the author or report issues by: https://github.com/appcell/OverwatchDataAnalysis/issues"""
        )
        self.notice.pack()

    def click_save(self):
        filename = filedialog.askdirectory(initialdir='~/')
        self.save_path.config(text=filename)

    def click_read(self):
        # self.root.
        filename = filedialog.askopenfilename(
            initialdir='~/OW/OverwatchDataAnalysis/videos')
        self.read_path.config(text=filename)

    def check_update(self):
        version = {
            'name': 'ORA OWL',
            'current_version': 0.1,
        }

    def info(self):
        info = {
            "name_team_left": "left",
            "name_team_right": "right",
            "name_players_team_left": [],
            "name_players_team_right": [],
            "video_path": "/",
            "output_path": "/",
        }
        frame_left = self.left_frame.pack_slaves()
        frame_right = self.right_frame.pack_slaves()

        info['name_team_left'] = frame_left[0].get()
        info['name_team_right'] = frame_right[0].get()
        #
        team_left = []
        team_right = []
        for i in range(1, 7):
            player_left = frame_left[i].get()
            team_left.append(player_left)
            player_right = frame_right[i].get()
            team_right.append(player_right)

        info['name_players_team_left'] = team_left
        info['name_players_team_right'] = team_right
        info['video_path'] = self.read_path['text']
        info['output_path'] = self.save_path['text']

        return info

    def show(self):
        self.root.mainloop()

    def show_finish_msg(self):
        tkMessageBox.showinfo('一个微小的弹窗', '保存成功!')

    def show_progress(self, progress):
        self.notice.insert(Tkinter.INSERT, str(progress))

    def run(self):
        self.game_instance = game.Game(OW.GAMETYPE_OWL, OW.ANALYZER_FPS)
        self.game_instance.set_game_info(self.info())
        self.game_instance.analyze(0, 0, is_test=False)
        self.game_instance.output_to_excel()
        self.show_finish_msg()
Exemplo n.º 53
0
class DATAin:
    def __init__(self, maestro):
        # Atributo de conteo'''
        self.botonClics = 0
        self.bandDATA = 3
        self.operacion=""
        self.cliente = ''
        self.Producto = ''
        self.alturaDATA = 0
        self.anchoDATA = 0
        self.largoDATA = 0
        self.Datos = []
        for i in range (7):
            self.Datos.append('')
            
        self.consoleSQL = PSQLmerma1()
        #gg = Tkk.Notebook(maestro)
        self.top = Toplevel(maestro)
        self.top.title('Introduce medidas de la caja')
        self.top.update_idletasks()
#        w = self.top.winfo_screenwidth()
#        h = self.top.winfo_screenheight()
#        size = tuple(int(_) for _ in self.top.geometry().split('+')[0].split('x'))
#        x = w/2 - size[0]/2
#        y = h/2 - size[1]/2
#        print size + (x, y)
#        
        self.top.geometry("+150+60")
        #self.top.iconbitmap('/home/pi/Desktop/ProgGUI/GUI/resources/ICO/IconoBCT.ico')
        
        #MARCO3 ESEL LINEZO DONDE SE DIBUJAN LAS PESTAÑAS
        self.marco3 = TTK.Notebook(self.top)

        # CREAMOS EL MARCO PARA CADA UNA DE LAS PESTAÑAS
        self.page1 = TTK.Frame(self.marco3)
        self.page2 = TTK.Frame(self.marco3)
        self.page3 = TTK.Frame(self.marco3)
        self.page4 = TTK.Frame(self.marco3)
        self.page5 = TTK.Frame(self.marco3)
       
        # AGREGAMOS EL MARCO A LAS PESTAÑAS Y SU NOMBRE
        self.marco3.add(self.page1, text='Dimensiones de la caja')
        self.marco3.add(self.page2, text='Descripción de la caja')
        self.marco3.add(self.page3, text='Descripción de la prueba')
        self.marco3.add(self.page4, text='Datos del cliente')
        self.marco3.add(self.page5, text='Resumen de datos')
        self.marco3.grid()
        
        # AGREGAGOS CONTENIDO A PESTAÑA 1
        self.IMGcaja = PhotoImage(file = '/home/pi/Desktop/InterfazG-BCT/resources/img/cajaDATA/caja.png')
        self.IMGancho= PhotoImage(file = '/home/pi/Desktop/InterfazG-BCT/resources/img/cajaDATA/anchoSelect.png')
        self.IMGlargo= PhotoImage(file = '/home/pi/Desktop/InterfazG-BCT/resources/img/cajaDATA/largoSelect.png')
        self.IMGalto = PhotoImage(file = '/home/pi/Desktop/InterfazG-BCT/resources/img/cajaDATA/altoSelect.png')
        
        self.cajaLB = Label(self.page1, image = self.IMGcaja)
        self.cajaLB.grid(row = 0, column = 4, rowspan = 5, columnspan = 3)
        
        self.txtLB = 'Seleccione un botón e ingrese \n las medidas en cm'
        self.LB = Label(self.page1, font =('Helvetica', 15), text = self.txtLB)
        self.LB.grid(row = 0, column = 0, columnspan = 4)
        
        self.CBdata = Text(self.page1, state="disabled", width=40, height=2, font=("Helvetica",15))
        self.CBdata.grid(row = 1, column = 0, columnspan = 4)
        
        self.anchoL = Label(self.page1, 
                            font =('Helvetica', 15), 
                            text = "")
        self.anchoL.grid(row =4, column = 4, sticky = 's')
        self.BTNancho = Button(self.page1, width=5, height=1, font=("Helvetica",15), text = 'Ancho', command =lambda: self.selectCB('an'))
        self.BTNancho.grid(row = 5, column = 4)
        self.largoL = Label(self.page1, 
                            font =('Helvetica', 15), 
                            text = "")
        self.largoL.grid(row =4, column = 5, sticky = 's')
        self.BTNlargo = Button(self.page1, width=5, height=1, font=("Helvetica",15), text = 'Largo', command =lambda: self.selectCB('la'))
        self.BTNlargo.grid(row = 5, column = 5)
        self.altoL  = Label(self.page1, 
                            font =('Helvetica', 15), 
                            text = "")
        self.altoL.grid(row =4, column = 6, sticky = 's')
        self.BTNalto = Button(self.page1, width=5, height=1, font=("Helvetica",15), text = 'Alto', command =lambda: self.selectCB('al'))
        self.BTNalto.grid(row = 5, column = 6)
        
        boton1 = self.crearBoton(1)
        boton2 = self.crearBoton(2)
        boton3 = self.crearBoton(3)
        boton4 = self.crearBoton(4)
        boton5 = self.crearBoton(5)
        boton6 = self.crearBoton(6)
        boton7 = self.crearBoton(7)
        boton8 = self.crearBoton(8)
        boton9 = self.crearBoton(9)
        boton0 = self.crearBoton(0,ancho=7)
        botonErase = self.crearBoton(u"\u232B",escribir=False)
        botonErase['background'] = "red"
        botonErase.grid(row = 2, column = 3)
        botonEnter = self.crearBoton(u"\u21B5",escribir=False)
        botonEnter['background'] = "green"
        botonEnter.grid(row = 3, column = 3)
        botondot = self.crearBoton('.')
        
        #Ubicación de los botones
        botones=[boton7, boton8, boton9,
                 boton4, boton5, boton6,
                 boton1, boton2, boton3,
                 boton0]
        contador=0
        for fila in range(2,5):
            for columna in range(3):
                botones[contador].grid(row=fila,column=columna)
                contador+=1
        #Ubicar el último botón al final
        botones[contador].grid(row=5,column=0,columnspan=2)
        botondot.grid(row = 5, column = 2)
        
        # AGREGAGOS CONTENIDO A PESTAÑA 2
        Label(self.page2, 
              font =('Helvetica', 15), 
              text = 'Seleccione:')\
              .grid(row = 0, column = 0,columnspan = 5)
              
        Label(self.page2, 
              font =('Helvetica', 15), 
              text = 'Estilo de caja')\
              .grid(row = 1, column = 0)
              
        self.listCaja = Combobox(self.page2,
                                 state="readonly",
                                 values = ["Caja troquelada", "Caja est" + u"\xe1" + "ndar"],
                                 font =('Helvetica', 15))
        self.listCaja.grid(row = 2, column = 0)
        Label(self.page2, 
              font =('Helvetica', 15), 
              text = '             ')\
              .grid(row = 2, column = 1)
        
        Label(self.page2, 
              font =('Helvetica', 15), 
              text = 'Tipo de flauta')\
              .grid(row = 1, column = 2)
        self.listFlauta = Combobox(self.page2,
                                   state="readonly",
                                   values = ["Corrugado sencillo B", "Corrugado sencillo C", "Corrugado sencillo E", "Doble corrugado BC", "Doble corrugado EB"],
                                   font =('Helvetica', 15))
        self.listFlauta.grid(row = 2, column = 2)
        Label(self.page2, 
              font =('Helvetica', 15), 
              text = '             ')\
              .grid(row = 2, column = 3)
              
              
        Label(self.page2, 
              font =('Helvetica', 15), 
              text = 'Dirección de la flauta')\
              .grid(row = 1, column = 4)
        self.listFlautaD= Combobox(self.page2,
                                   state="readonly",
                                   values = ["Horizontal", "Vertical"],
                                   font =('Helvetica', 15))
        self.listFlautaD.grid(row = 2, column = 4)
                                   
        Label(self.page2, 
              font =('Helvetica', 15), 
              text = '             ')\
              .grid(row = 3, column = 0, columnspan = 3)
        
        Label(self.page2, 
              font =('Helvetica', 15), 
              text = 'Grado del material')\
              .grid(row = 4, column = 0)
        self.listGradoM= Combobox(self.page2,
                                   state="readonly",
                                   values = ["No aplica", "20 ECT", "21 ECT", "23 ECT", "26 ECT", "29 ECT", "32 ECT", "44 ECT", "48 ECT", "50 ECT", "61 ECT", "71 ECT"],
                                   font =('Helvetica', 15))
        self.listGradoM.grid(row = 5, column = 0)
                                   
        Label(self.page2, 
              font =('Helvetica', 15), 
              text = 'Tipo de unión')\
              .grid(row = 4, column = 2)
        self.listUnion= Combobox(self.page2,
                                   state="readonly",
                                   values = ["Pegado", "Grapado", "Armado automático"],
                                   font =('Helvetica', 15))
        self.listUnion.grid(row = 5, column = 2)
        
        # AGREGAMOS CONTEIDO A PAGE3
        Label(self.page3, 
              font =('Helvetica', 15), 
              text = 'Método de cierre')\
              .grid(row = 0, column = 0)
        self.listCierre= Combobox(self.page3,
                                   state="readonly",
                                   values = ["Conforme a la TAPPI T 804", "Otro", "No aplica"],
                                   font =('Helvetica', 15))
        self.listCierre.grid(row = 1, column = 0)
                                   
        Label(self.page3, 
              font =('Helvetica', 15), 
              text = '             ')\
              .grid(row = 0, column = 1)
              
        Label(self.page3, 
              font =('Helvetica', 15), 
              text = 'Orientación de la prueba')\
              .grid(row = 0, column = 2)
        self.listOrientaC= Combobox(self.page3,
                                   state="readonly",
                                   values = ["Arriba a abajo", "Extremo a extremo", "Lado a lado"],
                                   font =('Helvetica', 15))
        self.listOrientaC.grid(row = 1, column = 2)
        
        self.IMGbct = Image.open(file = '/home/pi/Desktop/InterfazG-BCT/resources/img/cajaDATA/CajaBIedit.png')
        
        self.cajaBCT = Label(self.page3, image = self.IMGbct)
        self.cajaBCT.grid(row = 2, column = 0, columnspan = 3)
        
        # AGREGAMOS CONTENIDO A PAGE 4
        self.txtLB = 'Ingresar datos o buscar por número de pedido'
        self.state = TTK.Label(self.page4, font =('Helvetica', 15), text = self.txtLB)
        self.state.grid(row = 0, column = 0, columnspan = 12)
        
        boton1 = self.crearBotonP4(1)
        boton2 = self.crearBotonP4(2)
        boton3 = self.crearBotonP4(3)
        boton4 = self.crearBotonP4(4)
        boton5 = self.crearBotonP4(5)
        boton6 = self.crearBotonP4(6)
        boton7 = self.crearBotonP4(7)
        boton8 = self.crearBotonP4(8)
        boton9 = self.crearBotonP4(9)
        boton0 = self.crearBotonP4(0)
        
        botonQ = self.crearBotonP4('Q')
        botonW = self.crearBotonP4('W')
        botonE = self.crearBotonP4('E')
        botonR = self.crearBotonP4('R')
        botonT = self.crearBotonP4('T')
        botonY = self.crearBotonP4('Y')
        botonU = self.crearBotonP4('U')
        botonI = self.crearBotonP4('I')
        botonO = self.crearBotonP4('O')
        botonP = self.crearBotonP4('P')
        botonA = self.crearBotonP4('A')
        botonS = self.crearBotonP4('S')
        botonD = self.crearBotonP4('D')
        botonF = self.crearBotonP4('F')
        botonG = self.crearBotonP4('G')
        botonH = self.crearBotonP4('H')
        botonJ = self.crearBotonP4('J')
        botonK = self.crearBotonP4('K')
        botonL = self.crearBotonP4('L')
        botonNN= self.crearBotonP4('Ñ')
        botonZ = self.crearBotonP4('Z')
        botonX = self.crearBotonP4('X')
        botonC = self.crearBotonP4('C')
        botonV = self.crearBotonP4('V')
        botonB = self.crearBotonP4('B')
        botonN = self.crearBotonP4('N')
        botonM = self.crearBotonP4('M')
        botondot = self.crearBotonP4('.')
        botonguion = self.crearBotonP4('-')
        botonguionb = self.crearBotonP4(',')
        botonErase = self.crearBotonP4(u"\u232B",escribir=False)
        botonErase['background'] = "red"
        botonErase.grid(row = 3, column = 11)
        botonEnter = self.crearBotonP4(u"\u21B5",escribir=False,alto=2)
        botonEnter['background'] = "green"
        botonEnter.grid(row = 1, column = 11, rowspan = 2, sticky = 's')
        botonSpace = Button(self.page4, text=u"\u2423", width=5, height=1, font=("Helvetica",15), command=lambda:self.clickP4(' ',True))
        botonSpace.grid(row = 4, column = 11)
        
        #Ubicación de los botones
        botones= [boton1, boton2, boton3, boton4, boton5, boton6, boton7, boton8, boton9, boton0,
                  botonQ, botonW, botonE, botonR, botonT, botonY, botonU, botonI, botonO, botonP, 
                  botonA, botonS, botonD, botonF, botonG, botonH, botonJ, botonK, botonL, botonNN, 
                  botonZ, botonX, botonC, botonV, botonB, botonN, botonM, botondot, botonguion, botonguionb]
        contador=0
        for fila in range(1,5):
            for columna in range(10):
                botones[contador].grid(row=fila,column=columna)
                contador+=1
        
        self.ChkSe = IntVar()
        self.RBCliente = Radiobutton(self.page4, text = 'Cliente',font =('Helvetica', 15), variable = self.ChkSe, value = 1)
        self.RBCliente.grid(row = 5, column = 2, columnspan = 2, sticky = 'w')
        
        self.RBProducto = Radiobutton(self.page4, text = 'Producto',font =('Helvetica', 15), variable = self.ChkSe, value = 2)
        self.RBProducto.grid(row = 5, column = 4, columnspan = 2, sticky = 'w')
        
        self.RBBuscar = Radiobutton(self.page4, text = 'Buscar por pedido',font =('Helvetica', 15), variable = self.ChkSe, value = 3)
        self.RBBuscar.grid(row = 5, column = 6, columnspan = 3, sticky = 'w')
        
        self.CBdata2 = Text(self.page4, state="disabled", width=40, height=1, font=("Helvetica",15))
        self.CBdata2.grid(row = 6, column = 0, columnspan = 12)
                
        self.clienteL = TTK.Label(self.page4, font =('Helvetica', 15), text = 'Cliente:')
        self.clienteL.grid(row = 7, column = 0, columnspan = 11, sticky = 'w')
        
        self.ProductoL = TTK.Label(self.page4, font =('Helvetica', 15), text = 'Producto:')
        self.ProductoL.grid(row = 8, column = 0, columnspan = 11, sticky = 'w')
        
        # AGREGAMOS CONTENIDO A PAGE 5
        Label(self.page5, 
              font =('Helvetica', 15), 
              text = '*                                                                                                                                                *').grid(row = 0,
#              text = '123456789_123456789_123456789_123465789_123456789_123456789_123456789_123456789_12',
              #text = '____________________________').grid(row = 0,
                                                                     column = 0,
                                                                     columnspan = 3)
        Label(self.page5, 
              font =('Helvetica', 15),
              text = '_________________________________________').grid(row = 0,
                                                                     column = 0,)
        
        Label(self.page5, 
              font =('Helvetica', 15),
              text = '_________________________________________').grid(row = 0,
                                                                     column = 1)
#        Label(self.page5, 
#              font =('Helvetica', 15),
#              text = '___________________________').grid(row = 0,
#                                                                     column = 2)
        Label(self.page5, 
              font =('Helvetica', 15), 
              text = 'Verifique los datos ingresado:').grid(row = 0,
                                                                     column = 0,
                                                                     columnspan = 2)
        self.StxtCliente = StringVar(value = '*')
        self.txtCliente = Label(self.page5, font = ('Helvetica', 15, 'italic'), text = '*Cliente:')
        self.txtCliente.grid(row = 1, column = 0, sticky = 'w')
        self.txtClienteL = Label(self.page5, font = ('Helvetica', 15), textvariable = self.StxtCliente)
        self.txtClienteL.place(x = 79, y = 28)
        
        self.StxtProducto = StringVar(value = '*')
        self.txtProducto = Label(self.page5, font = ('Helvetica', 15, 'italic'), text = '*Producto: ')
        self.txtProducto.grid(row = 2, column = 0, columnspan = 2, sticky = "w")
        self.txtProductoL = Label(self.page5, font = ('Helvetica', 15), textvariable = self.StxtProducto)
        self.txtProductoL.place(x = 99, y = 56)
        
        self.StxtLargo = StringVar(value = '*')
        self.txtLargo = Label(self.page5, font = ('Helvetica', 15, 'italic'), text = '*Largo:')
        self.txtLargo.grid(row = 3, column = 0, sticky = "w")
        self.txtLargoL = Label(self.page5, font = ('Helvetica', 15), textvariable = self.StxtLargo)
        self.txtLargoL.place(x= 69, y = 84)
        
        self.StxtAlto = StringVar(value = '*')
        self.txtAlto = Label(self.page5, font = ('Helvetica', 15, 'italic'), text = '*Alto:')
        self.txtAlto.place(x = 310, y = 84)
        self.txtAltoL = Label(self.page5, font = ('Helvetica', 15), textvariable = self.StxtAlto)
        self.txtAltoL.place(x = 363, y = 84)
        
        self.StxtAncho = StringVar(value = '*')
        self.txtAncho = Label(self.page5, font = ('Helvetica', 15, 'italic'), text = '*Ancho: ')
        self.txtAncho.place(x= 590, y = 84)
        self.txtAnchoL = Label(self.page5, font = ('Helvetica', 15), textvariable = self.StxtAncho)
        self.txtAnchoL.place(x= 666, y = 84)
        
        self.StxtStlCj = StringVar(value = '*')
        self.txtStlCj = Label(self.page5, font = ('Helvetica', 15, 'italic'), text = '*Estilo caja:')
        self.txtStlCj.grid(row = 4, column = 0, sticky = "w")
        self.txtStlCjL = Label(self.page5, font = ('Helvetica', 15), textvariable = self.StxtStlCj)
        self.txtStlCjL.place(x= 110, y = 112)
        
        self.StxtTpFlt = StringVar(value = '*')
        self.txtTpFlt = Label(self.page5, font = ('Helvetica', 15, 'italic'), text = '*Tipo de flauta:')
        self.txtTpFlt.grid(row = 4, column = 1, sticky = "w")
        self.txtTpFltL = Label(self.page5, font = ('Helvetica', 15), textvariable = self.StxtTpFlt)
        self.txtTpFltL.place(x= 594, y = 112)
        
        self.StxtDrccnFlt = StringVar(value = '*')
        self.txtDrccnFlt = Label(self.page5, font = ('Helvetica', 15, 'italic'), text = '*Dirección de la flauta: ')
        self.txtDrccnFlt.grid(row = 5, column = 0, sticky = "w")
        self.txtDrccnFltL = Label(self.page5, font = ('Helvetica', 15), textvariable = self.StxtDrccnFlt)
        self.txtDrccnFltL.place(x= 216, y = 140)
        
        self.StxtGrdMtrl = StringVar(value = '*')
        self.txtGrdMtrl = Label(self.page5, font = ('Helvetica', 15, 'italic'), text = '*Grado del material: ')
        self.txtGrdMtrl.grid(row = 5, column = 1, sticky = "w")
        self.txtGrdMtrlL = Label(self.page5, font = ('Helvetica', 15), textvariable = self.StxtGrdMtrl)
        self.txtGrdMtrlL.place(x= 640, y = 140)
        
        
        self.StxtTpUnn = StringVar(value = '*')
        self.txtTpUnn = Label(self.page5, font = ('Helvetica', 15, 'italic'), text = '*Tipo de unión: ')
        self.txtTpUnn.grid(row = 6, column = 0, sticky = "w")
        self.txtTpUnnL = Label(self.page5, font = ('Helvetica', 15), textvariable = self.StxtTpUnn)
        self.txtTpUnnL.place(x= 138, y = 168)
        
        self.StxtMtdCrr = StringVar(value = '*')
        self.txtMtdCrr = Label(self.page5, font = ('Helvetica', 15, 'italic'), text = '*Método de cierre: ')
        self.txtMtdCrr.grid(row = 6, column = 1, sticky = "w")
        self.txtMtdCrrL = Label(self.page5, font = ('Helvetica', 15), textvariable = self.StxtMtdCrr)
        self.txtMtdCrrL.place(x= 623, y = 168)
        
        self.StxtOrntcn = StringVar(value = '*')
        self.txtOrntcn = Label(self.page5, font = ('Helvetica', 15, 'italic'), text = '*Orientación de la prueba: ')
        self.txtOrntcn.grid(row = 7, column = 0, sticky = "w")
        self.txtOrntcnL = Label(self.page5, font = ('Helvetica', 15), textvariable = self.StxtOrntcn)
        self.txtOrntcnL.place(x= 243, y = 197)
        
        cc = Button(self.page5, font = ('Helvetica', 15, "bold"), text = 'Cerrar', bg = "red", command = self.cerrarB)#.place(x = 20, y = 20)
        cc.grid(row = 8, column = 0, columnspan = 2)
        
        # OBTENER LO QUE CONTIENEN CADA LISTA
        self.listCaja.bind("<<ComboboxSelected>>", self.getList)
        self.listCierre.bind("<<ComboboxSelected>>", self.getList)
        self.listFlauta.bind("<<ComboboxSelected>>", self.getList)
        self.listFlautaD.bind("<<ComboboxSelected>>", self.getList)
        self.listGradoM.bind("<<ComboboxSelected>>", self.getList)
        self.listOrientaC.bind("<<ComboboxSelected>>", self.getList)
        self.listUnion.bind("<<ComboboxSelected>>", self.getList)
        
        self.top.protocol("WM_DELETE_WINDOW", self.cerrar)
        
    def motion(self, event):
        self.posy.set(event.y)
        self.posx.set(event.x)
        
    def selectCB(self,selecc):
        if selecc == 'al':
            self.LB['text'] = 'Usted selecciono alto'
            self.cajaLB['image'] = self.IMGalto
            self.bandDATA = 0
        elif selecc == 'an':
            self.LB['text'] = 'Usted selecciono ancho'
            self.cajaLB['image'] = self.IMGancho
            self.bandDATA = 1
        elif selecc == 'la':
            self.LB['text'] = 'Usted selecciono largo'
            self.cajaLB['image'] = self.IMGlargo
            self.bandDATA = 2
        
    def crearBoton(self, valor, escribir=True, ancho=5, alto=1):
        return Button(self.page1, text=valor, width=ancho, height=alto, font=("Helvetica",15), command=lambda:self.click(valor,escribir))
        
    def crearBotonP4(self, valor, escribir=True, ancho=5, alto=1):
        return Button(self.page4, text=valor, width=ancho, height=alto, font=("Helvetica",15), command=lambda:self.clickP4(valor,escribir))
        
    def conteo(self):
        self.botonClics += 1
        self.btnCLK['text'] = 'Clics totales = ' + str(self.botonClics)
        
        
    def click(self, texto, escribir):
        if not escribir:
            if texto==u"\u21B5" and self.operacion!="" and self.bandDATA != 3:
                if self.bandDATA == 0:
                    try:
                        self.alturaDATA = float(self.operacion)
                        self.LB['text'] = 'Usted ingreso ' + str(self.alturaDATA) + 'cm en altura'
                        self.altoL['text'] = str(self.alturaDATA) + 'cm'
                        self.StxtAlto.set(str(self.alturaDATA) + 'cm')
                        self.changeTXT(self.StxtAlto, str(self.alturaDATA) + 'cm', self.txtAlto, 'Alto:')
                    except ValueError:
                        self.LB['text'] = 'Atención \n El dato ingresado no es un número válido,\n favor de verificar'
                        
                elif self.bandDATA == 1:
                    try:
                        self.anchoDATA = float(self.operacion)
                        self.LB['text'] = 'Usted ingreso ' + str(self.anchoDATA) + 'cm en ancho'
                        self.changeTXT(self.StxtAncho, str(self.anchoDATA) + 'cm', self.txtAncho, 'Ancho:')
                        self.anchoL['text'] = str(self.anchoDATA) + 'cm'
                    except ValueError:
                        self.LB['text'] = 'Atención \n El dato ingresado no es un número válido,\n favor de verificar'
                elif self.bandDATA == 2:
                    try:
                        self.largoDATA = float(self.operacion)
                        self.LB['text'] = 'Usted ingreso ' + str(self.largoDATA ) + 'cm en largo'
                        self.changeTXT(self.StxtLargo, str(self.largoDATA ) + 'cm', self.txtLargo, 'Largo:')
                        self.largoL['text'] = str(self.largoDATA ) + 'cm'
                    except ValueError:
                        self.LB['text'] = 'Atención \n El dato ingresado no es un número válido,\n favor de verificar'
                print 'Hola desde borrar'
                self.operacion = ''
                self.limpiarPantalla()
            elif texto==u"\u232B":
                self.operacion=""
                self.limpiarPantalla()
        #Mostrar texto
        else:
            self.operacion+=str(texto)
            self.mostrarEnPantalla(texto)
        return
    
    def clickP4(self, texto, escribir):
        self.ChkSel = int(self.ChkSe.get())
        print self.ChkSel
        if not escribir:
            if texto==u"\u21B5" and self.operacion!="" and self.ChkSel != 0:
                print 'gg'
                if self.ChkSel == 1:
                    self.cliente = self.operacion
                    self.clienteL['text'] = 'Cliente: ' + str(self.cliente)
                    self.changeTXT(self.StxtCliente, str(self.cliente), self.txtCliente, 'Cliente:')
                elif self.ChkSel == 2:
                    self.Producto = self.operacion
                    self.ProductoL['text'] = 'Producto: ' + str(self.Producto)
                    self.changeTXT(self.StxtProducto, str(self.Producto), self.txtProducto, 'Producto:')
                elif self.ChkSel == 3:
                    self.top.iconify()
                    self.consoleSQL.consulta('pedido', str(self.operacion))
                    try:
                        self.cliente = self.consoleSQL.cliente
                        self.clienteL['text'] = 'Cliente: ' + str(self.cliente)
                        self.changeTXT(self.StxtCliente, str(self.cliente), self.txtCliente, 'Cliente:')
                        self.Producto = self.consoleSQL.producto
                        self.ProductoL['text'] = 'Producto: ' + str(self.Producto)
                        self.changeTXT(self.StxtProducto, str(self.Producto), self.txtProducto, 'Producto:')
                    except:
                        tkMessageBox.showerror('Atención','No se encontró el pedido favor de verificar')
                self.operacion = ''
                self.limpiarPantalla(2)
            elif texto==u"\u232B":
                self.operacion=""
                self.limpiarPantalla(2)
            elif self.ChkSel == 0:
                self.top.iconify()
                tkMessageBox.showerror("Atención", 'Debe seleccionar una opción')
        #Mostrar texto
        else:
            self.operacion+=str(texto)
            self.mostrarEnPantalla(texto, 2)
        self.top.deiconify()
        return
    
    def changeTXT(self, StringVarTXT, setStr, LabelTXT, txtLabel):
        StringVarTXT.set(setStr)
        LabelTXT['text'] = txtLabel
        LabelTXT['font'] = ('Helvetica', 15, "bold")
        
    def limpiarPantalla(self, cb = 1):
        if cb ==2:
            self.CBdata2.configure(state="normal")
            self.CBdata2.delete("1.0", END)
            self.CBdata2.configure(state="disabled")
        else:
            self.CBdata.configure(state="normal")
            self.CBdata.delete("1.0", END)
            self.CBdata.configure(state="disabled")
        return
    

    def mostrarEnPantalla(self, valor, cb = 1):
        if cb == 2:
            self.CBdata2.configure(state="normal")
            self.CBdata2.insert(END, valor)
            self.CBdata2.configure(state="disabled")
        else:
            self.CBdata.configure(state="normal")
            self.CBdata.insert(END, valor)
            self.CBdata.configure(state="disabled")
        return
    
    def getList(self, event):
        self.CheckList(self.listCaja, 0, self.StxtStlCj, 'Estilo caja: ', self.txtStlCj)
        self.CheckList(self.listFlauta, 1, self.StxtTpFlt, 'Tipo de flauta: ', self.txtTpFlt)
        self.CheckList(self.listFlautaD, 2, self.StxtDrccnFlt, 'Dirección de  la flauta: ', self.txtDrccnFlt)
        self.CheckList(self.listGradoM, 3, self.StxtGrdMtrl, 'Grado del material: ', self.txtGrdMtrl)
        self.CheckList(self.listUnion, 4, self.StxtTpUnn, 'Tipo de unión: ', self.txtTpUnn)
        self.CheckList(self.listCierre, 5, self.StxtMtdCrr, 'Método de cierre: ', self.txtMtdCrr)
        self.CheckList(self.listOrientaC, 6, self.StxtOrntcn, 'Orientación de la prueba: ', self.txtOrntcn)
        #hola
        
    def CheckList(self, lista, num_list, StrVarL, txt, labelTXT,):
        gg = lista.get()
        print gg
        if gg != '':
            self.Datos[num_list] = lista.get()
            if num_list == 0:
                if self.Datos[0] == (u'Caja est\xe1ndar'):
                    self.Datos[0] = str('Caja estándar')
            elif num_list == 4:
                if self.Datos[4] == (u'Armado autom\xe1tico'):
                    self.Datos[4] = ('Armado automático')
            StrVarL.set(self.Datos[num_list])
            labelTXT['text'] = txt
            labelTXT['font'] = ('Helvetica', 15, "bold")
            
        
    def cerrar(self):
        self.top.iconify()
        tkMessageBox.showinfo("Atención", "Si desea salir, debe hacerlo desde el botón ubicado en la pestaña de Resumen de datos.")
        self.top.deiconify()
        
    def cerrarB(self):
        self.top.iconify()
        respuesta=tkMessageBox.askyesno("Atención", "Usted esta a punto de salir, ¿Los datos ingresados son los correctos?")
        if respuesta==True:
            self.top.destroy()
        try:
            self.top.deiconify()
        except:
            print "Ventana cerrada"
            
#ventana = Tk()
#final = DATAin(ventana)
#ventana.mainloop()
Exemplo n.º 54
0
class QuestionGUI(object):
    def __init__(self, parent): 
        self.frame = Frame(parent) 
        self.frame.pack(fill=BOTH,expand=1)
        self.parent = parent 
        self.parent.bind_all("<Key>", key_controller)
        self.initUI()
        self.makeStatusWindow()

    def initUI(self):
        self.parent.title("Jeopardy")        
        self.text = Text(self.frame,bg=utils.bg_blue,fg=utils.mod_question_color)
        self.text.pack(fill=BOTH,expand=1)
        self.text.tag_config("a",justify=CENTER,font=tkFont.Font(family="Courier",weight="bold",size=50),wrap=WORD)
        self.text.tag_config("b",justify=CENTER,font=tkFont.Font(family="Courier",weight="bold",size=50),wrap=WORD,foreground="red")

    def drawQuestion(self,question,draw_question):
        self.text.delete(1.0, END)
        tag = "a" if draw_question else "b"
        self.text.insert(INSERT,question.category+"\n",tag)
        self.text.insert(END,"$"+str(question.value)+"\n",tag)
        if draw_question:
            self.text.insert(END,question.clue,"a")
        else:
            self.text.insert(END,question.answer,"a")
    def makeStatusWindow(self):
        self.status_window = Toplevel(self.parent)
        self.status_window.geometry("1300x700+0+0")
        self.status_board = StatusGUI(self.status_window)
    def switchWindows(self):
        x_q,y_q = self.parent.winfo_x(),self.parent.winfo_y()
        x_s,y_s = self.status_window.winfo_x(),self.status_window.winfo_y()
        self.parent.geometry("1300x700+{}+{}".format(x_s,y_s))
        self.status_window.geometry("1300x700+{}+{}".format(x_q,y_q))
    def displayFinalJeopardy(self,player_to_scores_dict):
        player_bets = {}
        player_answers = {}
        self.parent.bind_all("<Key>", null_controller)
        player_names = [t[0] for t in sorted(player_to_scores_dict.items(), key= lambda x : x[1])]
        current_player_index = [0]
        def final_controller(event):
            char = event.char
            if char == 'y':
                right = True
            if char == 'n':
                right = False
            if char == 'y' or char == 'n':
                multiplier = 1 if right else -1
                name = player_names[current_player_index[0]]
                state.awardPoints(name,multiplier*player_bets[name])
                displayFinalJeopardyResult()
        def displayResults(player_name,player_score,player_bet,player_answer):
            self.text.insert(INSERT,"{}'s Answer: {}\nBet: {}".format(player_name,player_answer,player_bet),"b")
        def displayFinalJeopardyResult():
            self.text.delete(1.0, END)
            for child in self.text.winfo_children():
                child.destroy()
            current_player_index[0] += 1
            if current_player_index[0] >= len(player_names):
                return
            current_player = player_names[current_player_index[0]]
            displayResults(current_player,player_to_scores_dict[current_player],player_bets[current_player],player_answers[current_player])
            self.parent.bind_all("<Key>", final_controller)

        def displayFinalJeopardyBet(player_name,player_score,answer=False):
            self.text.delete(1.0, END)
            for child in self.text.winfo_children():
                child.destroy()
            mode = "Bet" if not answer else "Answer"
            self.text.insert(INSERT,"Final Jeopardy\n{}'s {} (${}):".format(player_name,mode,str(player_score)),"b")
            e = Entry(self.text)
            e.pack()
            def placeBet():
                if not answer:
                    try:
                        bet = int(e.get())
                    except ValueError:
                        e.insert(0,"not a number")
                        return
                    if bet < 0 or bet > player_score:
                        e.insert(0,"invalid bet")
                        return
                    player_bets[player_name] = bet
                else:
                    input = e.get()
                    player_answers[player_name] = input
                
                current_player_index[0] += 1
                if current_player_index[0] >= len(player_names):
                    if not answer:
                        current_player_index[0] = 0
                        next_player = player_names[0]
                        displayFinalJeopardyBet(next_player,player_to_scores_dict[next_player],answer=True)
                    else:
                        current_player_index[0] = 0
                        displayFinalJeopardyResult()
                else:
                    next_player = player_names[current_player_index[0]]
                    displayFinalJeopardyBet(next_player,player_to_scores_dict[next_player],answer=answer)
            b = Button(self.text, text="Place Bet", width=10, command=placeBet)
            b.pack()
            
            
        displayFinalJeopardyBet(player_names[current_player_index[0]],player_to_scores_dict[player_names[current_player_index[0]]])
Exemplo n.º 55
0
    def help_about(self):

        """Shows an 'about' modal dialog.

        Callback method called by tk.

        """

        about_win = Toplevel(self.root)

        # Set up dialog

        lbl = Label(about_win, text="Video Poker")
        lbl.grid(row=0, column=0, padx=10, pady=(10, 0), sticky=W + N)
        lbl = Label(about_win, text="by Charles Raymond Smith")
        lbl.grid(row=1, column=0, padx=10, pady=(0, 7), sticky=W + N)
        lbl = Label(about_win, text="Adapted from video poker by Paul Griffiths")
        lbl.grid(row=2, column=0, padx=10, pady=(0, 7), sticky=W + N)
        lbl = Label(about_win, text="Written in Python, with tkinter.")
        lbl.grid(row=3, column=0, padx=10, pady=7, sticky=W + N)
        lbl = Label(about_win, text="Copyright 2017 Charles Raymond Smith")
        lbl.grid(row=4, column=0, padx=10, pady=(7, 0), sticky=W + N)
        lbl = Label(about_win, text="Email: [email protected]")
        lbl.grid(row=5, column=0, padx=10, pady=(0, 21), sticky=W + N)
        lbl = Label(about_win, text="This program is free software: you can " +
            "redistribute it and/or modify it under the terms")
        lbl.grid(row=6, column=0, columnspan=2,
                 padx=10, pady=0, sticky=W + N)
        lbl = Label(about_win, text="of the GNU General Public License as " +
            "published by the Free Software Foundation, either")
        lbl.grid(row=7, column=0, columnspan=2,
                 padx=10, pady=(0, 0), sticky=W + N)
        lbl = Label(about_win, text="version 3 of the License, or " +
            "(at your option) any later version.")
        lbl.grid(row=8, column=0, columnspan=2,
                 padx=10, pady=(0, 21), sticky=W + N)
        lbl = Label(about_win, text="This program is distributed in " +
            "the hope that it will be useful, but WITHOUT ANY WARRANTY;")
        lbl.grid(row=9, column=0, columnspan=2,
                 padx=10, pady=0, sticky=W + N)
        lbl = Label(about_win, text="without even the implied " +
            "warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR")
        lbl.grid(row=10, column=0, columnspan=2,
                 padx=10, pady=(0, 0), sticky=W + N)
        lbl = Label(about_win, text="PURPOSE. See the " +
            "GNU General Public License for more details.")
        lbl.grid(row=11, column=0, columnspan=2,
                 padx=10, pady=(0, 21), sticky=W + N)
        lbl = Label(about_win, text="You should have received a " +
            "copy of the GNU General Public License along with this")
        lbl.grid(row=12, column=0, columnspan=2,
                 padx=10, pady=(0, 0), sticky=W + N)
        lbl = Label(about_win, text="program. If not, see " +
            "<http://www.gnu.org/licenses/>.")
        lbl.grid(row=13, column=0, columnspan=2,
                 padx=10, pady=(0, 21), sticky=W + N)
        img = PhotoImage(file="{0}27.gif".format(self.gifdir))
        lbl = Label(about_win, image=img)
        lbl.grid(row=0, column=1, rowspan=5, padx=10, pady=10, sticky=N + E)

        btn = Button(about_win, text="OK", command=about_win.quit)
        btn.grid(row=14, column=0, columnspan=2,
                 padx=0, pady=(0, 10), ipadx=30, ipady=3)

        # Show dialog

        about_win.transient(self.root)
        about_win.parent = self.root
        about_win.protocol("WM_DELETE_WINDOW", about_win.destroy)
        about_win.geometry("+{0}+{1}".format(self.root.winfo_rootx() + 50,
                                           self.root.winfo_rooty() + 50))
        about_win.title("About Video Poker")
        about_win.focus_set()
        about_win.grab_set()
        about_win.mainloop()
        about_win.destroy()
Exemplo n.º 56
0
 def do_a_turn(self):
     # roll die
     die1_val = random.randint(1,6)
     die2_val = random.randint(1,6)
     # TODO: potentially simulate die motion like in matlab version
     # change die values on screen
     self.dice1_strvar.set(str(die1_val))
     self.dice2_strvar.set(str(die2_val))
     
     # check dice conditions
     ethan_val = int(self.ethan_strvar.get())
     player_val = int(self.player_strvars[self.player_turn].get())
     if (die1_val+die2_val == 4):
         # player gets ethan's stuff
         player_val = player_val + ethan_val
         ethan_val = 0
     elif (die1_val+die2_val == 2) and self.ethan_eyes:
         # player loses it all to ethan
         ethan_val = player_val + ethan_val
         player_val = 0
     else:
         # player loses one chip to ethan
         ethan_val = ethan_val + 1
         player_val = player_val - 1
     self.ethan_strvar.set(str(ethan_val))
     self.player_strvars[self.player_turn].set(str(player_val))
     # check for the lose condition
     total_chips = 0
     num_players_positive = 0
     for x in self.player_strvars:
         if int(x.get()) > 0:
             num_players_positive = num_players_positive + 1
         total_chips = total_chips + int(x.get())
     if total_chips == 0:
         # everybody loses
         error_dlg = Toplevel(master=self.main_window)
         error_dlg.geometry("%dx%d+%d+%d" % 
             (INIT_WINDOW_WIDTH, INIT_WINDOW_HEIGHT, X_POS, Y_POS))
         error_dlg.title( "LOSERS" );
         error_dlg.grab_set();
         error_msg = Message(error_dlg, aspect=300, text="EVERYBODY LOSES, AE2015")
         error_msg.pack();
         error_button = Button(error_dlg, text="OK", \
                             command=lambda: self.destroy_all(error_dlg));
         error_button.pack();
         error_dlg.update();
     elif (num_players_positive == 1) and (player_val > ethan_val):
         #win condition, only for player who just moved
         player_name = self.player_name_list[self.player_turn].get();
         error_dlg = Toplevel(master=self.main_window)
         error_dlg.geometry("%dx%d+%d+%d" % 
             (INIT_WINDOW_WIDTH, INIT_WINDOW_HEIGHT, X_POS, Y_POS))
         error_dlg.title( "WINNER" );
         error_dlg.grab_set();
         error_msg = Message(error_dlg, aspect=300, text="GOOD JOB %s, YOU BEAT ETHAN" % (player_name) )
         error_msg.pack();
         error_button = Button(error_dlg, text="OK", \
                                 command=error_dlg.destroy);
         error_button.pack();
         error_dlg.update();
     else:
         # game isn't over, increment turn to next positive player
         self.player_frame_list[self.player_turn].config(relief='flat', \
             borderwidth=0)
         num_players = len(self.player_strvars)
         found_next = 0
         self.current_turn = self.current_turn + 1
         while (found_next == 0):
             self.player_turn = (self.player_turn + 1) % num_players
             if int(self.player_strvars[self.player_turn].get()) > 0:
                 found_next = 1
         self.player_frame_list[self.player_turn].config(relief='raised', \
             borderwidth=2)    
     return
Exemplo n.º 57
0
class UIEngine(Thread, Notify):
    """
        Handle a Tk Interface

    """

    interface_id = -1

    def __init__(self):
        UIEngine.interface_id += 1
        Notify.__init__(self)
        Thread.__init__(self)
        # This condition will notify the main thread when init is over
        self._wait_init_event = Event()
        # Run the UI thread
        self.start()
        # Wait for the initialisation of the ui
        #   to continue
        self._wait_init_event.wait(10)


    def _init_tk_window(self):
        """
            Initialize the window for the Tk Interface

        """
        # Create the instance
        if UIEngine.interface_id == 0:
            self._root = Tk() 
        else:
            self._root = Toplevel() 
        # Resize the window
        # compute h according to the table
        h = UITable.TABLE_HEIGHT
        # fixed size for the width
        w = 1200
        # translate it in string
        dim = str(w) + "x" + str(h)
        self._root.geometry(dim)


    def _init_table(self):
        """
            Init the table frame
            This part is responsible for all

        """
        self._table = UITable(self._root)
        self._table.set_method(CONSOLE_RED, \
                               lambda msg, c=True: self.add_message(msg, c)) 


    def _init_side_pannel(self):
        """
            The side pannel 
        
        """
        self._side_pannel = UISidePannel(self._root)
        # Initialize the quit callback
        quit_callback = lambda: self._event[EVT_UI_PLAYER_LEFT]( \
                                 self._table.interface_player)
        self._side_pannel.set_method(EVT_CONTROL_QUIT, quit_callback) 


    def _init_ui(self):
        """
            Sets the interface and enter the tk mainloop

        """
        # Init the interface
        self._init_tk_window()
        # Init the game parts 
        self._init_table()
        # Init the other part
        self._init_side_pannel()


    def run(self):
        """
            This method will be called when the UI thread starts.
            It initialise and launch the UI. 

        """
        # Launch the initialisation
        self._init_ui()
        # Notify the end of the initialisation 
        self._wait_init_event.set()
        # Release the condition, now useless
        self._wait_init_event.clear()
        # Enter the infinite loop, see you lata
        if UIEngine.interface_id == 0: 
            self._root.mainloop()

    
    def set_reference_player(self, p):
        """
            Reference player is the player who manage the interface
            Will be positioned South
            @param p    future reference player 
            
        """
        self._table.interface_player = p


    def new_round(self):
        """
            Notification for the beginning of a new round

        """
        self._table.new_round()


    def new_bid(self, bid):
        """
            A new bid has been made, need to forward it to the table

        """
        self._table.new_bid(bid)


    def new_deal(self):
        """
            Notification for the beginning of a deal 

        """
        self._table.new_deal()


    def card_played(self, p, c):
        """

            Notification that the card c has been played by player p
            @param c    tuple (val, col) of the card played
            @param p    id of the player that played the card

        """
        self._table.card_played(p, c)


    def end_of_trick(self, p):
        """
            Notification that the current trick is finished 
            (it should reasonnably mean that four cards have
            been played since the beginning of the trick)
            @param p    id of the player that wins the trick

        """
        self._table.end_of_trick(p)


    def get_card(self, p, playable):
        """
            Wait for the user p to choose a card between
            the possible ones given in playable
            @param p            id of the player expected to play
            @param playable     list of cards that can be played

        """
        return self._table.get_card(p, playable)


    def get_coinche(self):
        """
            Wait for the user to coinche. 

        """
        return self._table.get_coinche()


    def get_bid(self, p, bidded, bid_list):
        """
            Wait for the user p to bid 
            the possible ones given in bid list 
            @param p            id of the player expected to play
            @param bidded       last 4 bids
            @param bid_list     list of possible bids

        """
        return self._table.get_bid(p, bidded, bid_list)


    def new_hand(self, player, hand):
        """
            Set a new hand hand for player player
            Method called by an event engine to refresh display
            @param player   id of the player that is given the hand
            @param hand list of tuples (val, col) composing the hand

        """
        self._table.new_hand(player, hand)


    def end_bidding(self):
        self._table.end_bidding()


    def add_player(self, p):
        """
            Add a player handled by the UI
            @param p    player handled  

        """
        self._table.add_player(p)


    def add_message(self, msg, red = False):
        """
            Add a message to the UIConsole

        """
        self._side_pannel.add_message(msg, red)


    def get_consoles(self):
        """
            Return the list of the consoles for this UI

        """
        return [self._side_pannel._console]


    def update_score(self, score):
        """
            Update the score in ui_table
            @param score    the new score

        """
        self._table.update_score(score)


    def belote(self, pid):
        """

        """
        self._table.belote(pid)

    def rebelote(self, pid):
        """

        """
        self._table.rebelote(pid)
         

    def set_method(self, evt_id, method):
        """
            Overwrite set_method
            Because UIEngine is only an entry-point, set_method need
                to be called on every child of UIEngine

        """
        self._event[evt_id] = method
        self._side_pannel.set_method(evt_id, method)
        self._table.set_method(evt_id, method)
Exemplo n.º 58
0
class controllerSettings():

    def createControllerWindow(self):

        #Creation of the main window
        self.controllerWindow = Toplevel()
        self.controllerWindow.title("Controller Settings")
        self.controllerWindow.geometry("400x310+450+200")
        self.controllerWindow.resizable(width=False, height=False)

        #Frame for the manual controller options
        self.k_controllerFrame = tk.Frame(self.controllerWindow)
        self.c_controllerFrame = tk.Frame(self.controllerWindow)
        self.instructionFrame = tk.Frame(self.controllerWindow)

        self.knownJsFrame=tk.Frame(self.k_controllerFrame,width=150,height=120)
        self.knownJsFrame.pack_propagate(0)
        self.chosenJsFrame=tk.Frame(self.c_controllerFrame,width=150,height=120)
        self.chosenJsFrame.pack_propagate(0)

        self.instrLabel = tk.Label(self.instructionFrame, text="Please select up " \
            "to two remote controllers from the recognized controller list. Alter" \
            "natively, scan for existing controllers and automatically add the " \
            "controller to the software.", anchor=tk.W, justify=tk.LEFT, wraplength = 400)
        self.instrLabel.pack()
        self.l1 = tk.Label(self.knownJsFrame, text="Recognized Controllers")
        self.l1.pack()
        self.l2 = tk.Label(self.chosenJsFrame, text="Selected Controller/s")
        self.l2.pack()
        self.knownListbox = tk.Listbox(self.knownJsFrame, height = 15, width = 29)
        self.knownListbox.insert(tk.END)

        for item in ["PS3 PowerA", "Xbox 360 Afterglow"]:
            self.knownListbox.insert(tk.END, item)

        self.chosenListbox = tk.Listbox(self.chosenJsFrame, height = 15, width = 29)
        self.chosenListbox.insert(tk.END)

        self.controllers = []
        self.controllers = self.retrieveControllers()

        if len(self.controllers) == 1:
            self.chosenListbox.insert(tk.END, self.controllers[0])
        elif len(self.controllers) == 2:
            self.chosenListbox.insert(tk.END, self.controllers[0])
            self.chosenListbox.insert(tk.END, self.controllers[1])

        self.closeBtn = tk.Button(self.controllerWindow, text ="Close", \
            command = self.controllerWindow.destroy, width = 12)

        self.okBtn = tk.Button(self.controllerWindow, text ="Okay", \
            width = 12)

        self.applyBtn = tk.Button(self.controllerWindow, text ="Apply Changes", \
            width = 16, command = self.selectedListBoxWriteout)

        self.addBtn = tk.Button(self.controllerWindow, text ="Add", \
            width = 10, command = self.addListBoxIndex)

        self.rmvBtn = tk.Button(self.controllerWindow, text ="Remove", \
            width = 10, command = self.rmvListBoxIndex)

        self.scanBtn = tk.Button(self.controllerWindow, text ="Scan for controllers...", \
            width = 16)

        self.knownListbox.pack()
        self.chosenListbox.pack()
        self.knownJsFrame.pack()
        self.chosenJsFrame.pack()
        self.instructionFrame.pack()
        self.k_controllerFrame.pack()
        self.c_controllerFrame.pack()
        self.closeBtn.pack()
        self.okBtn.pack()
        self.applyBtn.pack()
        self.addBtn.pack()
        self.rmvBtn.pack()
        self.scanBtn.pack()

        self.k_controllerFrame.place(x = 20, y = 85)
        self.c_controllerFrame.place(x = 210, y = 85)

        self.closeBtn.place(x = 300, y = 275)
        self.okBtn.place(x = 200, y = 275)
        self.applyBtn.place(x = 20, y = 275)
        self.addBtn.place(x = 40, y = 210)
        self.rmvBtn.place(x = 240, y = 210)
        self.scanBtn.place(x = 230, y = 50)

    def addListBoxIndex(self):

        self.chosenInt = 0
        self.chosenInt = self.chosenListbox.size()

        if self.chosenInt >= 2:
            tkm.showerror("Error", "You can only add up to two controllers.")
        else:
            self.listBoxStr = ""
            self.listBoxStr = self.knownListbox.get(tk.ACTIVE)

            self.chosenListbox.insert(tk.END, self.listBoxStr)

    def rmvListBoxIndex(self):

        self.chosenInt = 0
        self.chosenInt = self.chosenListbox.index(tk.ACTIVE)

        self.chosenListbox.delete(self.chosenInt)

    def selectedListBoxWriteout(self):

        self.tempStr = ""
        self.contrlStr1 = ""
        self.contrlStr2 = ""
        self.success = 0
        if self.chosenListbox.size() == 0:
            tkm.showerror("Error", "No controllers selected.")
        
        elif self.chosenListbox.size() == 1:
            self.contrlStr1 = self.chosenListbox.get(0)
            self.tempStr = "controllerdata{" + self.contrlStr1 + "}\n"
            self.tempStr = self.tempStr.replace (" ", "_")
            self.success = 1

        elif self.chosenListbox.size() == 2:
            self.contrlStr1 = self.chosenListbox.get(0)
            self.contrlStr2 = self.chosenListbox.get(1)
            self.tempStr = "controllerdata{" + self.contrlStr1 + ","\
            + self.contrlStr2 + "}\n"
            self.tempStr = self.tempStr.replace (" ", "_")
            self.success = 1

        if self.success == 1:
            self.data = []
            with open('config.txt', 'r') as file:
                # read a list of lines into data
                self.data = file.readlines()

            for x in range (0, len(self.data)):
                if self.data[x].find("controllerdata") != -1:
                    self.data[x] = self.tempStr
                    print self.data[x]

            with open('config.txt', 'w') as file:
                file.writelines(self.data)

        self.main.destroy()
        self.createMainWindow()