示例#1
0
class MyFirstGUI:
    LABEL_TEXT = [
        "This is our first GUI!",
        "Actually, this is our second GUI.",
        "We made it more interesting...",
        "...by making this label interactive.",
        "Go on, click on it again.",
    ]
    def __init__(self, master):
        self.master = master
        master.title("A simple GUI")

        self.label_index = 0
        self.label_text = StringVar()
        self.label_text.set(self.LABEL_TEXT[self.label_index])
        self.label = Label(master, textvariable=self.label_text)
        self.label.bind("<Button-1>", self.cycle_label_text)
        self.label.pack()

        self.greet_button = Button(master, text="Greet", command=self.greet)
        self.greet_button.pack()

        self.close_button = Button(master, text="Close", command=master.quit)
        self.close_button.pack()

    def greet(self):
        print("Greetings!")

    def cycle_label_text(self, event):
        self.label_index += 1
        self.label_index %= len(self.LABEL_TEXT) # wrap around
        self.label_text.set(self.LABEL_TEXT[self.label_index])
示例#2
0
文件: gui.py 项目: jwdafoe/ContactPro
 def show_about(self):
     about = About(self.master, "About {}".format(self.version[:-5]), self.logo)
     Label(about.frame, text=self.version, style="atitle.TLabel").grid(sticky="w")
     Label(about.frame, text="Developer:  Joel W. Dafoe").grid(pady="6", sticky="w")
     link = Link(about.frame, text="http://cyberdatx.com", foreground="blue", cursor="hand2")
     link.grid(sticky="w")
     link.bind("<Button-1>", lambda e: webbrowser.open("http://cyberdatx.com"))
     Label(about.frame, text=self.description, wraplength=292).grid(columnspan=2, pady=6, sticky=W)
class LoginGui(object):
    def __init__(self, root):
        self.welcome_text = 'Prihlaseny' if User.is_loaded_session() else ""

        self.response_text = StringVar(root, value=self.welcome_text)

        self.top_frame = Frame(root, width=400, height=400)

        self.middle_frame = Frame(root, width=300, height=300)

        self.top_frame.pack(fill="both", expand=True, padx=20, pady=20)
        self.middle_frame.place(in_=self.top_frame, anchor='c', relx=.5, rely=.5)

        self.l_email = Label(self.middle_frame, text="Email")
        self.e_email = Entry(self.middle_frame)

        self.l_pass = Label(self.middle_frame, text="Password")
        self.e_pass = Entry(self.middle_frame, show="*")

        self.l_sign_up = Label(self.middle_frame, text="Sign up", fg='blue', cursor='hand2')

        self.l_req_result = Label(self.middle_frame, textvariable=self.response_text)

        self.b_submit = Button(self.middle_frame, text="Login")

        self.l_email.grid(row=0, sticky=E)
        self.e_email.grid(row=0, column=1)
        self.l_pass.grid(row=1, column=0, sticky=E)
        self.e_pass.grid(row=1, column=1)
        self.b_submit.grid(row=2, column=1, sticky=E)
        self.l_sign_up.grid(row=3, column=1, sticky=E)
        self.l_req_result.grid(row=4)

        self.l_sign_up.bind('<Button-1>', self.sing_up_callback)
        self.b_submit.bind('<Button-1>', self.login)

        self.root = root
        self.root.mainloop()

    def login(self, event):
        response = User.login(self.e_email.get(), self.e_pass.get())
        self.response_text.set(response)
        if User.is_loaded_session():
            self.root.destroy()

    @staticmethod
    def sing_up_callback(event):
        webbrowser.open_new(Config.SIGN_UP_URL)

    @staticmethod
    def show_login():
        root = tkinter.Tk(className="Productivity optimizer")
        LoginGui(root)
        root.mainloop()
示例#4
0
文件: gui.py 项目: jwdafoe/DrvTool
 def show_about(self):
     about = Toplevel(self.master)
     about.title('About {}'.format(self.version[:-5]))
     about.focus()
     about.resizable(0, 0)
     logo_lbl = Label(about, image=self.logo)
     logo_lbl.image = self.logo
     logo_lbl.grid(row=0, column=0, padx='7 11', pady=13, sticky='n')
     about_frame = Frame(about, padding='0 10 10 10')
     about_frame.grid(row=0, column=1)
     Label(about_frame, text=self.version).grid(sticky='w')
     Label(about_frame, text='Developer:  Joel W. Dafoe').grid(pady='6', sticky='w')
     link = Link(about_frame, text='http://cyberdatx.com', foreground='blue', cursor='hand2')
     link.grid(sticky='w')
     link.bind('<Button-1>', lambda e: webbrowser.open('http://cyberdatx.com'))
     Label(about_frame, text=self.description, wraplength=292).grid(columnspan=2, pady=6, sticky='w')
     cls_btn = Button(about_frame, text='OK', command=about.destroy)
     cls_btn.grid(column=1, sticky='e')
     cls_btn.focus()
     about.bind('<Return>', lambda e: cls_btn.invoke())
示例#5
0
    def append_chords(self, chords=[]):
        '''pass a [list] of Chords to the Accordion object'''

        self.update_idletasks()
        row = 0
        width = max([c.winfo_reqwidth() for c in chords])
        
        for c in chords:
            i = PhotoImage() # blank image to force Label to use pixel size
            label = Label(self, text=c.title,
                          image=i,
                          compound='center',
                          width=width,
                          anchor='w',
                          font=('Franklin Gothic Book', 11),
                          bg=self.style['title_bg'],
                          fg=self.style['title_fg'],
                          cursor=self.style['cursor'],
                          bd=1, relief='flat')
            
            label.grid(row=row, column=0, sticky='nsew')
            c.grid(row=row+1, column=0, sticky='nsew')
            c.grid_remove()
            row += 2
            
            label.bind('<Button-1>', lambda e,
                       c=c: self._click_handler(c))
            label.bind('<Enter>', lambda e,
                       label=label, i=i: label.configure(bg=self.style['highlight'],fg=self.style['highlight_fg']))
            label.bind('<Leave>', lambda e,
                       label=label, i=i: label.configure(bg=self.style['title_bg'],fg=self.style['title_fg']))
示例#6
0
class Photo:

	def __init__(self, **kwargs):
		self.repr = kwargs['repr']
		self.path = kwargs['path']

	def config(self, **kwargs):
		if 'path' in kwargs:
			self.path = kwargs['path']
			self.picture = Image.open(self.path)
			self.picture = self.picture.resize((200, 200), Image.ANTIALIAS)
			self.image = ImageTk.PhotoImage(self.picture)
			self.label.config(image=self.image)

	def place(self, **kwargs):
		self.parent = kwargs['parent']
		self.row = kwargs['row']
		self.column = kwargs['column']

		self.picture = Image.open(self.path)
		self.image = ImageTk.PhotoImage(self.picture)

		self.label = Label(self.parent, image=self.image, bd=1)
		self.label.grid(row=self.row, column=self.column)
		self.label.bind('<Button-1>', lambda e: self.label.focus_set())

	def getData(self):
		return self.path

	def setData(self, data):
		#le sigh
		if data == '' or 'N/A': return
		self.config(path=data)

	def hide(self):
		self.label.grid_forget()
示例#7
0
packing_list = [btn1, btn2, btn3, btn4, btn5]
for packing_index, to_be_packed in enumerate(packing_list):
    to_be_packed.grid(row=0, column=packing_index)
# lf1.pack(side='top', fill='both', expand=False, padx=40)
lf1.pack(fill='both', padx=10, pady=5)
# text1.pack(side=BOTTOM, padx=10)
#text1.place(x=125, y=450, anchor='nw')
text1.pack(fill='both', padx=10, pady=5)

for i, task in enumerate(tasks):
    label_text_i = StringVar(tk, '', '')
    label_text_i.set(task_names[i])
    label_texts.append(label_text_i)
    label = Label(lf1, textvariable=label_text_i)
    cmd = Command(i)
    label.bind('<Button-1>', cmd.run)
    label.pack()
    labels.append(label)


text1.bind('<Return>', submit_note)


def attention_test():
    global current_task_index, tasks, ds_velocity

    test_results = []

    while True:
        while not is_any_task_running():
            time.sleep(0.1)
示例#8
0
    def init_grid(self):
        self.grid_cells = []

        # the background
        self.game_scene = Frame(self,
                                bg=c.BACKGROUND_COLOR_GAME,
                                width=c.SIZE,
                                height=c.SIZE)
        self.game_scene.grid()

        # game grid
        for i in range(c.GRID_LEN * c.GRID_LEN):
            cell = Frame(self.game_scene, bg=c.CELL_COLOR_EMPTY)
            cell.grid(row=i // c.GRID_LEN,
                      column=i % c.GRID_LEN,
                      padx=c.GRID_PADDING,
                      pady=c.GRID_PADDING)
            t = Label(master=cell,
                      text="",
                      bg=c.CELL_COLOR_EMPTY,
                      fg=c.TEXT_COLOR,
                      justify=CENTER,
                      font=c.FONT,
                      width=4,
                      height=2)
            t.bind("<Button-1>", lambda event, i=i: self.move_cell(i))
            t.grid()

            self.grid_cells.append(t)

        # create game over dialog but dont place it
        self.game_over_dialog = Frame(self)
        f = Frame(self.game_over_dialog, bg="white", padx=10, pady=10)
        f.grid()
        # the excellent image
        image = PhotoImage(file="excellent.png")
        l = Label(f, image=image)
        l.image = image
        l.grid(columnspan=2, padx=10, pady=5)
        # tell the performance
        Label(f, text="It took you", bg="white", fg="#534648",
              font="Arial 16").grid(row=1, column=0, pady=10)
        Label(f,
              textvariable=self.score,
              bg="white",
              fg="#534648",
              font="Arial 16 bold").grid(row=1, column=1, pady=10)
        # play again button
        btn = Label(f,
                    text="Play Again",
                    bg="#3d2963",
                    fg="white",
                    font="Arial 22 bold",
                    justify=CENTER,
                    pady=10,
                    padx=20,
                    cursor="hand2")
        btn.bind("<Enter>", lambda event: btn.config(bg="tomato"))
        btn.bind("<Leave>", lambda event: btn.config(bg="#3d2963"))
        btn.bind("<Button-1>", self.new_game)
        btn.grid(columnspan=2, pady=5)
示例#9
0
    def __init__(self, master):
        global recipient, amount, balancetext
        # global transactionstatus
        global sessionprofittext, minuteprofittext, hourlyprofittext, dailyprofittext
        global balanceusdtext, ducopricetext
        global transactionstext
        global curr_bal, profit_array

        textFont3 = Font(size=12, weight="bold")
        textFont2 = Font(size=22, weight="bold")
        textFont = Font(size=12, weight="normal")
        rsize = Font(size=10)

        self.master = master
        master.geometry("720x420")
        master.resizable(False, False)
        master.title("Duino-Coin Wallet")
        master.configure(background=backgroundColor)

        Label(
            master,  # UP - DOWN
            background="#7bed9f",
            font=rsize,
            width="10",
            height="100").place(relx=.0, rely=.0)

        Label(
            master,  # LEFT - RIGHT
            background="#f5cd79",
            font=rsize,
            width="150",
            height="4").place(relx=.0, rely=.0)

        Label(
            master,  # SQUARE
            background="#ff7f50",
            font=rsize,
            width="10",
            height="4").place(relx=.0, rely=.0)

        balancetext = StringVar()
        balancetext.set("Please wait...")
        balanceLabel = Label(master,
                             textvariable=balancetext,
                             background="#f5cd79",
                             foreground=foregroundColor,
                             font=textFont2)
        balanceLabel.place(relx=.15, rely=.07)

        Label(master,
              text="1 DUCO = $" + str(ducofiat),
              background="#f5cd79",
              foreground=foregroundColor,
              font=textFont).place(relx=.6, rely=.11)

        Label(master,
              text="BALANCE",
              background="#f5cd79",
              foreground=foregroundColor,
              font=textFont).place(relx=.1525, rely=.0155)

        Label(master,
              text="FIAT BALANCE",
              background="#f5cd79",
              foreground=foregroundColor,
              font=textFont).place(relx=.6, rely=.015)

        balanceusdtext = StringVar()
        balanceusdtext.set("Please wait...")
        balanceusdLabel = Label(master,
                                textvariable=balanceusdtext,
                                background="#f5cd79",
                                foreground=foregroundColor,
                                font=textFont3)
        balanceusdLabel.place(relx=.6, rely=.06)

        duco = ImageTk.PhotoImage(Image.open(resources + "duco.png"))
        duco.image = duco
        ducoLabel = Label(master, background="#ff7f50", image=duco)
        ducoLabel.place(relx=.005, rely=.0025)
        ducoLabel.bind("<Button>", openWebsite)

        transactions = ImageTk.PhotoImage(
            Image.open(resources + "transactions.png"))
        transactions.image = transactions
        transactionsLabel = Label(master,
                                  background="#7bed9f",
                                  image=transactions)
        transactionsLabel.place(relx=.005, rely=.2)
        transactionsLabel.bind("<Button>", openTransactions)

        calculator = ImageTk.PhotoImage(
            Image.open(resources + "calculator.png"))
        calculator.image = calculator
        calculatorLabel = Label(master, background="#7bed9f", image=calculator)
        calculatorLabel.place(relx=.005, rely=.37)
        calculatorLabel.bind("<Button>", openCalculator)

        original = Image.open(resources + "stats.png")
        resized = original.resize((64, 64), Image.ANTIALIAS)

        stats = ImageTk.PhotoImage(resized)
        stats.image = stats
        statsLabel = Label(master, background="#7bed9f", image=stats)
        statsLabel.place(relx=.005, rely=.53)
        statsLabel.bind("<Button>", openStats)

        settings = ImageTk.PhotoImage(Image.open(resources + "settings.png"))
        settings.image = settings
        settingsLabel = Label(master, background="#7bed9f", image=settings)
        settingsLabel.place(relx=.005, rely=.82)
        settingsLabel.bind("<Button>", openSettings)

        Label(master,
              text="RECIPIENT",
              font=textFont,
              background=backgroundColor,
              foreground=foregroundColor).place(relx=.15, rely=.2)

        def clear_recipient_placeholder(self):
            recipient.delete("0", "100")

        recipient = Entry(master,
                          background="#87ebff",
                          foreground=foregroundColor,
                          border="0",
                          font=textFont,
                          width="20")
        recipient.place(relx=.1525, rely=.255)
        recipient.insert("0", "revox")
        recipient.bind("<FocusIn>", clear_recipient_placeholder)

        Label(master,
              text="AMOUNT",
              font=textFont,
              background=backgroundColor,
              foreground=foregroundColor).place(relx=.15, rely=.32)

        def clear_amount_placeholder(self):
            amount.delete("0", "100")

        amount = Entry(master,
                       background="#87ebff",
                       foreground=foregroundColor,
                       border="0",
                       font=textFont,
                       width="20")
        amount.place(relx=.1525, rely=.375)
        amount.insert("0", "1.7")
        amount.bind("<FocusIn>", clear_amount_placeholder)

        def changeDucoColor(handler):
            sendLabel.configure(image=send2)

        def changeDucoColor2(handler):
            sendLabel.configure(image=send)

        send = ImageTk.PhotoImage(Image.open(resources + "send.png"))
        send.image = send
        send2 = ImageTk.PhotoImage(Image.open(resources + "send2.png"))
        send2.image = send2
        sendLabel = Label(master, background="#FEEEDA", image=send)
        sendLabel.place(relx=.45, rely=.25)
        sendLabel.bind("<Button-1>", sendFunds)
        sendLabel.bind("<Enter>", changeDucoColor)
        sendLabel.bind("<Leave>", changeDucoColor2)

        # transactionstatus = StringVar()
        # transactionLabel = Label(master, textvariable=transactionstatus,
        # 	font=textFont,
        # 	background=backgroundColor,
        # 	foreground=foregroundColor).place(relx=.15, rely=.435)

        Label(master,
              text="PROFIT",
              background="#feeeda",
              foreground=foregroundColor,
              font=textFont3).place(relx=.6, rely=.2)

        sessionprofittext = StringVar()
        sessionprofittext.set("Please wait - calculating...")
        sessionProfitLabel = Label(master,
                                   textvariable=sessionprofittext,
                                   background="#feeeda",
                                   foreground=foregroundColor,
                                   font=textFont)
        sessionProfitLabel.place(relx=.6, rely=.25)

        minuteprofittext = StringVar()
        minuteProfitLabel = Label(master,
                                  textvariable=minuteprofittext,
                                  background="#feeeda",
                                  foreground=foregroundColor,
                                  font=textFont)
        minuteProfitLabel.place(relx=.6, rely=.3)

        hourlyprofittext = StringVar()
        hourlyProfitLabel = Label(master,
                                  textvariable=hourlyprofittext,
                                  background="#feeeda",
                                  foreground=foregroundColor,
                                  font=textFont)
        hourlyProfitLabel.place(relx=.6, rely=.35)

        dailyprofittext = StringVar()
        dailyprofittext.set("")
        dailyProfitLabel = Label(master,
                                 textvariable=dailyprofittext,
                                 background="#feeeda",
                                 foreground=foregroundColor,
                                 font=textFont)
        dailyProfitLabel.place(relx=.6, rely=.4)

        Label(master,
              text="LOCAL TRANSACTIONS",
              background="#feeeda",
              foreground=foregroundColor,
              font=textFont3).place(relx=.15, rely=.5)

        transactionstext = StringVar()
        transactionstext.set("")
        transactionstextLabel = Label(master,
                                      textvariable=transactionstext,
                                      background="#feeeda",
                                      foreground=foregroundColor,
                                      font=textFont,
                                      justify=LEFT)
        transactionstextLabel.place(relx=.15, rely=.5525)

        github = ImageTk.PhotoImage(Image.open(resources + "github.png"))
        github.image = github
        githubLabel = Label(master, background="#FEEEDA", image=github)
        githubLabel.place(relx=.805, rely=.875)
        githubLabel.bind("<Button-1>", openGitHub)

        exchange = ImageTk.PhotoImage(Image.open(resources + "exchange.png"))
        exchange.image = exchange
        exchangeLabel = Label(master, background="#FEEEDA", image=exchange)
        exchangeLabel.place(relx=.865, rely=.875)
        exchangeLabel.bind("<Button-1>", openExchange)

        discord = ImageTk.PhotoImage(Image.open(resources + "discord.png"))
        discord.image = discord
        discordLabel = Label(master, background="#FEEEDA", image=discord)
        discordLabel.place(relx=.925, rely=.875)
        discordLabel.bind("<Button-1>", openDiscord)

        root.iconphoto(True, PhotoImage(file=resources + "duco.png"))
        start_balance = getBalance()
        curr_bal = start_balance
        calculateProfit(start_balance)
        updateBalanceLabel()

        root.mainloop()
示例#10
0
class MyNewGUI:

    # This member variable (field) is our list of strings for the click event
    # wired up to the lblMessage control.
    LABEL_TEXT = [
        "This is our first GUI!", "Actually, this is our second GUI.",
        "We've made it more interesting . . . ",
        ". . . by making this label interactive.",
        "Go ahead, click on me again."
    ]

    # This is our 'Pythonic' constructor.
    def __init__(self, master):
        self.master = master
        master.title("A simple GUI")

        # Set up the variables to handle rotating thru the list of strings.
        self.label_index = 0
        self.label_text = StringVar()
        self.label_text.set(self.LABEL_TEXT[self.label_index])

        # Define our controls and place them on the form using 'pack'.
        self.lblTitleBar = Label(master,
                                 bg='maroon',
                                 fg='white',
                                 font=('Helvetica', 18),
                                 text="This is the Python GUI called Tkinter!")
        self.lblTitleBar.pack(fill='x')

        # This is the label control that will respond to the click event.
        self.lblMessage = Label(master,
                                bg='maroon',
                                fg='white',
                                font=('Arial', 13),
                                textvariable=self.label_text)
        # This is the customer event handler for the label that handles the left
        # mouse button click when the pointer is over the control.
        self.lblMessage.bind('<Button-1>', self.cycle_label_text)
        self.lblMessage.pack(fill='x')

        # This is the button that will change the Title text when clicked.
        self.btnGreet = Button(master,
                               bg='black',
                               fg='white',
                               font=('Times', 12),
                               text="Greet",
                               command=self.greet)
        self.btnGreet.pack(fill='x')

        # This is the button that will close the app
        self.btnClose = Button(master,
                               bg='black',
                               fg='white',
                               font=('Times', 12),
                               text="Close",
                               command=master.quit)
        self.btnClose.pack(fill='x')

    # This is the method used to change the text in the Title label.
    def greet(self):

        self.lblTitleBar.config(
            text="Howdy, Bitches!! Welcome to the Mothership!")

    # This is the method to handle cycling thru our list of strings to be displayed.
    def cycle_label_text(self, event):

        self.label_index += 1
        self.label_index %= len(self.LABEL_TEXT)  # wrap around
        self.label_text.set(self.LABEL_TEXT[self.label_index])
    dict = createtb.gets()
    print(dict)


lists = ['text_in', 'text_s', 'fone_c', 'text_c']


def f2(*arg):
    dict = createtb.gets()
    for x in dict:
        for b in dict[x]:
            if x in lists:
                dict[x][b] = random.randrange(0, 7, 1)
            else:
                dict[x][b] = random.randrange(0, 2, 1)
    createtb.sets(dict)


tmp_place = Frame(root, bd=1)
bit = Label(tmp_place, text='ok', width=10, height=3)

bit.grid(row=0, column=0, sticky="w")

bit.bind('<Button-1>', f2)
bit.bind('<Button-3>', f1)
tmp_place.grid(row=1, column=0, sticky="w")

print('ok')
root.mainloop()
print('main exit')
    def body(self, master):
        dialogframe = Frame(master, width=536, height=225)
        self.dialogframe = dialogframe
        dialogframe.pack()

        self.RadioGroup_1_StringVar = StringVar()

        self.make_LabelFrame_1(
            self.dialogframe)  #  LabelFrame: Colors : at Main(5,1)
        self.make_Label_1(
            self.dialogframe
        )  #       Label: Left Click Background : at Main(2,1)
        self.make_Label_2(
            self.dialogframe
        )  #       Label: Right Click Foreground : at Main(3,1)
        self.make_Label_3(
            self.dialogframe
        )  #       Label: Luminance and Contrast Ratio shown above : at Main(4,1)
        self.make_RadioGroup_1(
            self.dialogframe)  #  RadioGroup: Sort By: : at Main(1,1)
        self.make_Radiobutton_1(
            self.RadioGroup_1)  # Radiobutton: HSV hue : at RadioGroup_1(1,1)
        self.make_Radiobutton_2(
            self.RadioGroup_1
        )  # Radiobutton: W3 Luminance : at RadioGroup_1(1,2)
        self.make_Radiobutton_3(
            self.RadioGroup_1
        )  # Radiobutton: HEX String : at RadioGroup_1(1,3)
        self.make_Radiobutton_4(
            self.RadioGroup_1
        )  # Radiobutton: Color Name : at RadioGroup_1(1,4)

        self.RadioGroup_1_StringVar.set("2")
        self.RadioGroup_1_StringVar_traceName = self.RadioGroup_1_StringVar.trace_variable(
            "w", self.RadioGroup_1_StringVar_Callback)
        # >>>>>>insert any user code below this comment for section "top_of_init"

        self.labelD = {}  # index=(row,col): value=Label object
        row = 0
        col = 0
        for (lum, lum_p05, h, r, g, b, cstr, name) in lum_sorted_colorL:
            lab = Label(self.LabelFrame_1,
                        text="  ",
                        width="3",
                        padx=0,
                        pady=0,
                        font=("times", "6", "normal"))
            lab.grid(row=row, column=col)
            self.labelD[(row, col)] = lab
            lab.configure(background=cstr, relief="raised")

            lab.bind("<Enter>", self.label_enter)
            lab.bind("<Leave>", self.label_leave)
            lab.bind("<ButtonRelease-1>", self.ColorPickLabel_LeftClick)
            lab.bind("<ButtonRelease-3>", self.ColorPickLabel_RightClick)

            col += 1
            if col >= COL_COUNT:
                col = 0
                row += 1

        self.tw = None
        self.bg_selectionT = lum_sorted_colorL[-1]  # set selection to white
        self.fg_selectionT = lum_sorted_colorL[0]  # set selection to black

        self.bg_label = None
        self.fg_label = None
示例#13
0
class TilePicker(Frame):
    def __init__(self, parent, doc, **kw):
        Frame.__init__(self, parent, **kw)
        self.doc = doc
        self.tilePicker = None
        self.attrPicker = None
        self.status = None
        self.curTile = 0
        self.lastX = self.lastY = 0
        self.setAttribute(0)
        self.tilePicker = Label(self,
                                image=self.tilePickerPI,
                                width=128,
                                borderwidth=0)
        self.tilePicker.grid(row=0, column=0)
        self.tilePicker.bind("<Button-1>", self.tilePickerCallback)
        self.attrPicker = Label(self, image=self.attrPickerPI, borderwidth=0)
        self.attrPicker.grid(row=1, column=0)
        self.attrPicker.bind("<Button-1>", self.attrPickerCallback)
        self.status = Label(self)
        self.status.grid(row=2, column=0)
        self.setStatus()

    def setAttribute(self, value):
        self.curAttribute = value & 0x03
        self.updateWidgets()

    def updateWidgets(self):
        self.tilePickerImage = renderChrFile(self.doc.chrdata, self.doc.clut,
                                             self.curAttribute * 4)
        self.tilePickerPI = ImageTk.PhotoImage(self.tilePickerImage)
        if self.tilePicker is not None:
            self.tilePicker.configure(image=self.tilePickerPI)

        previewTile = self.doc.renderTile(self.curTile, self.curAttribute)
        self.attrPickerImage = renderAttrPicker(previewTile, self.doc.clut,
                                                self.curAttribute)
        self.attrPickerPI = ImageTk.PhotoImage(self.attrPickerImage)
        if self.attrPicker is not None:
            self.attrPicker.configure(image=self.attrPickerPI)

        self.setStatus()

    def setTile(self, tile):
        self.curTile = tile
        self.setAttribute(self.curAttribute)

    def setStatus(self):
        if self.status is None:
            return
        addr = 0x2000 | (self.lastY << 5) | self.lastX
        label = (
            "tile $%02x attr %d\naddr $%04x (%d, %d)" %
            (self.curTile, self.curAttribute, addr, self.lastX, self.lastY))
        self.status.configure(text=label)

    def tilePickerCallback(self, event):
        if event.x >= 0 and event.x < 128 and event.y >= 0 and event.y < 128:
            tileX = event.x // 8
            tileY = event.y // 8
            newTileNo = tileY * 16 + tileX
            #print("mouse was clicked on tile", newTileNo)
            self.setTile(newTileNo)
            return
        print("mouse was clicked at (%d, %d)" % (event.x, event.y))

    def attrPickerCallback(self, event):
        if event.x >= 0 and event.x < 128:
            attr = event.x // 32
            #print("mouse was clicked on attribute", attr)
            self.setAttribute(attr)
            return
        print("mouse was clicked at (%d, %d)" % (event.x, event.y))
示例#14
0
class GUI:
    def __init__(self, master):
        """initialize GUI"""
        self.root = master
        self.on = True
        Tk().withdraw()

        self.starttime = datetime.now()

        # status bar, info for user
        self.statusString = StringVar()
        self.statusText = 'Ready'
        self.statusString.set(self.statusText)

        self.lvlStatus = StringVar()
        self.ifmStatus = StringVar()

        self.active = 0  # 0 - inactive state, 1 - active (in motion), 2 - steady (waiting while taking data)
        self.auto = 0

        # COMPARATOR MOTION CONTROL
        self.step = StringVar()  # mm
        self.begin = StringVar()  # mm
        self.end = StringVar()  # mm

        self.autoVal = IntVar()

        self.labelTop = StringVar()
        self.labelTop.set('VERTICAL COMPARATOR')

        # LABELS ON BUTTONS
        self.label10 = StringVar()  # start/stop
        self.label21 = StringVar()  # manual
        self.label22 = StringVar()  # auto
        self.label31 = StringVar()  # step
        self.label32 = StringVar()  # start
        self.label33 = StringVar()  # stop
        self.label51 = StringVar()  # read interferometer
        self.label52 = StringVar()  # read digi level

        self.autoVal.set(0)

        # init PLC, interferometer and level
        self.plc = PLC(comsettings['PLCPORT'], int(comsettings['PLCBAUD']))
        self.conn = self.plc.conn
        self.ifm = IFM(comsettings['IFMPORT'], int(comsettings['IFMBAUD']))
        self.lvl = LVL(comsettings['LVLPORT'], int(comsettings['LVLBAUD']))

        self.observer = ''  # operator

        self.label10.set({0: 'START', 1: 'STOP', 2:'STOP'}[self.active])  # start/stop
        self.setStatus({0: 'ready', 1: 'active', 2:'steady'}[self.active])
        self.label21.set('MANUAL')  # manual
        self.label22.set('AUTO')  # auto

        self.label31.set('LOW')  # start height
        self.label32.set('HIGH')  # stop height
        self.label33.set('STEP')  # step

        self.label51.set('READ IFM')  # read interferometer
        self.label52.set('READ LVL')  # read digi level

        self.timestring = StringVar()
        self.connstring = StringVar()

        # self.queue = queue.Queue()
        self.timerthread = threading.Thread(target=self.timer)
        self.timerthread.start()

        self.readdata = ''
        self.connthread = threading.Thread(target=self.checkconnection)
        self.connthread.start()

        self.statusthread = threading.Thread(target=self.checkstatus)
        self.statusthread.start()

        self.autologthread = threading.Thread(target=self.autolog)
        self.autologthread.start()

        # starttimer()
        # startautolog()
        # startautoserialcheck()

    # def toggleStartStop(self):
    #    # if start then stop else otherwise
    #    # change button and text color if possible
    #    pass

    def timer(self):
        while self.on:
            dt = datetime.now() - self.starttime
            self.timestring.set('%-10s' % str(dt).split('.')[0])
            time.sleep(1)

    def autolog(self, timeout=60):
        while self.on:
            print('Autolog')
            s, low, hi, step, ifm, lvl, obs = '', '', '', '', '', '', ''
            try:
                s = self.statusText
                low = self.lowEntry.get().strip()
                hi = self.hiEntry.get().strip()
                step = self.stepEntry.get().strip()
                ifm = IFM().read()
                lvl = LVL().read()
                obs = self.entryObserver.get().strip()
            except:
                print('problem with values')
            log('AUTOLOG! status: %s, low: %s, hi: %s, step: %s, ifm: %s, lvl: %s, obs: %s' % (
            s, low, hi, step, ifm, lvl, obs))
            time.sleep(timeout)

    def checkconnection(self):
        connection = False
        while self.on:
            if self.conn:
                try:
                    d = self.conn.read(1)
                    self.readdata += d
                    connection = True
                except:
                    self.conn.close()
                    try:
                        self.connect()
                    except:
                        connection = False
            else:
                try:
                    self.connect()
                except:
                    connection = False
            self.connstring.set({True: 'isConn', False: 'notConn'}[connection])
            time.sleep(0.5)

    def checkstatus(self):
        st = None
        if self.conn:
            try:
                st = self.plc.query('status')
                if st == commands['ACTIVE']:
                    self.plc.status = 'active'
                elif st == commands['INACTIVE']:
                    self.status = 'ready'
                else:
                    self.status = 'unknown'
            except:
                self.status = 'unknown'
        else:
            self.status = 'not connected'

    def evaluateEntries(self):
        s, b, e = self.stepEntry, self.beginEntry, self.endEntry
        res = [None, None, None]
        for i in range(3):
            try:
                res[i] = float([s, b, e][i])
            except:
                pass  # leave it None
        if b > e and s > 0:  # if step is negative, it can move downwards (from hi to low)
            b, e = e, b  # otherwise it begin and end must be changed if b>e
        elif b < e and s < 0:
            b, e = e, b

            # INPUT IN MM !! cannot recognize 0.5mm from 0.5m  step or 3mm vs 3m end
        # input values converted to mm
        # [s,b,e] = [i*1000. if (i is not None and i<5.) else i for i in [s,b,e]]
        return s, b, e

    def emptyRow(self, nrow):
        Label(self.fr, text="", bg=bgcolor).grid(row=nrow, column=0)

    def setStatus(self, text):
        self.statusText = text
        self.statusString.set(self.statusText)

    def setLvlStatus(self, text):
        self.lvlStatus.set(text)

    def setIfmStatus(self, text):
        self.ifmStatus.set(text)

    def getIfm(self):
        ifm = IFM()
        response = ifm.read()
        if not response: response = "No response"
        self.setIfmStatus(response)
        return response

    def getLevel(self):
        lvl = LVL()  # možno naèíta� pri __init__
        response = lvl.read()
        if not response: response = "No response"
        self.setLvlStatus(response)
        return response

    #    #set stop button
    #    def setStop(self):
    #        pass
    #
    #    #set start
    #    def setStart(self):
    #        pass

    # toggle start stop
    def startStop(self):
        self.active = not self.active
        self.label10.set({0: 'START', 1: 'STOP'}[self.active])
        self.setStatus({0: 'ready', 1: 'active'}[self.active])

        self.butStartStop.configure(bg=startstopbg[self.active],
                                    fg=startstopfg[self.active])

        self.observer = self.entryObserver.get().strip()

        if not self.active:
            log('CMP stopped %s' % self.observer)
        else:
            log('CMP started %s' % self.observer)

        if self.active:
            pass  # action after comparator is stopped
        else:
            pass  # action after comparator is started

    def getEntries(self):
        return self.stepEntry, self.beginEntry, self.endEntry

    def close(self):
        self.on = False
        if self.active:
            self.startStop()
        self.root.destroy()
        self.root.quit()

    def gotoLow(self):
        low = None
        self.setStatus('Going to LOW')
        try:
            low = float(self.lowEntry.get().strip())
        except:
            pass
        pass  # move carriage to set low
        return low

    def gotoHi(self):
        hi = None
        self.setStatus('Going to HIGH')
        try:
            hi = float(self.hiEntry.get().strip())
        except:
            pass
        pass  # move carriage to set low
        return hi

    def moveStep(self):
        pos = self.plc.getPos()
        step = 0
        try:
            step = float(self.stepEntry.get().strip())
        except:
            pass
        targetpos = pos + step

        if step != 0:
            self.setStatus('Moving to %f' % targetpos)
            self.plc.moveto(targetpos)
        return targetpos

    def resetLvlStatus(self):
        self.lvlStatus.set('')

    def resetIfmStatus(self):
        self.ifmStatus.set('')

    def mainDialog(self):

        self.basicframe = Frame(self.root)
        self.basicframe.grid()
        self.basicframe.configure(bg=bgcolor)

        self.fr = Frame(self.basicframe)
        self.fr.grid(row=0, column=0, sticky='new')  # , sticky='W')
        self.fr.configure(bg=bgcolor)

        # Grid.rowconfigure(root, 0, weight=1)
        Grid.columnconfigure(root, 0, weight=1)

        self.emptyRow(0)

        Label(self.fr, textvariable=self.labelTop,
              justify='center', bg=bgcolor, font=("Calibri", 24)
              ).grid(row=1, column=0, columnspan=3, sticky='we')

        self.emptyRow(2)

        Label(self.fr, text='STATUS:', justify='left', anchor='w',
              bg=bgcolor, fg=statuscolor, font=("Calibri", 12)
              ).grid(row=3, column=0, sticky='we', padx=(5, 0))

        self.statusLine = Label(self.fr, textvariable=self.statusString,
                                justify='left', anchor='w', bg=bgcolor, fg=statuscolor,
                                font=("Calibri", 14, "bold")
                                ).grid(row=3, column=1, columnspan=2, sticky='we')

        self.emptyRow(4)

        self.butStartStop = Button(self.fr, textvariable=self.label10,
                                   command=self.startStop,
                                   bg=startstopbg[self.active],
                                   fg=startstopfg[self.active],
                                   font=("Calibri", 16, "bold"),
                                   width=10)
        self.butStartStop.grid(row=5, column=1, sticky='nsew')

        # AUTO / MANUAL  self.my_var.set(1)
        self.butManual = Radiobutton(self.fr, text="MANUAL",
                                     variable=self.auto,
                                     value=0,
                                     width=15,
                                     justify='center',
                                     # bg=buttoncolor2,
                                     bg="moccasin",
                                     indicatoron=0)  # self.exit_root)
        self.butManual.grid(row=5, column=0, sticky='ew', padx=(0, 10))
        # self.butManual.configure(state='selected')

        self.butAuto = Radiobutton(self.fr, text="AUTO",
                                   variable=self.auto,
                                   value=1,
                                   width=15, justify='center',
                                   # bg=buttoncolor2,
                                   bg="moccasin",
                                   indicatoron=0)  # self.exit_root)
        self.butAuto.grid(row=5, column=2, sticky='ew', padx=(10, 0))

        self.emptyRow(6)
        self.emptyRow(7)

        # put Labels here

        Label(self.fr, textvariable=self.label31, justify='center',
              bg=bgcolor, fg=statuscolor, font=("Calibri", 10)
              ).grid(row=8, column=0, sticky='we')
        Label(self.fr, textvariable=self.label32, justify='center',
              bg=bgcolor, fg=statuscolor, font=("Calibri", 10)
              ).grid(row=8, column=1, sticky='we')
        Label(self.fr, textvariable=self.label33, justify='center',
              bg=bgcolor, fg=statuscolor, font=("Calibri", 10)
              ).grid(row=8, column=2, sticky='we')

        # input boxes: step start stop (mm)
        self.lowEntry = Entry(self.fr, width=20, bd=3, justify='right',
                              bg=inputbox, fg=statuscolor)
        self.lowEntry.grid(row=9, column=0, sticky='we')  # , columnspan=2)
        # SET DEFAULT LOW
        # self.lowEntry.delete(0,END)
        # self.lowEntry.insert(0, MINPOS)

        self.hiEntry = Entry(self.fr, width=20, bd=3, justify='right',
                             bg=inputbox, fg=statuscolor)
        self.hiEntry.grid(row=9, column=1, sticky='we')  # , columnspan=2)
        # SET DEFAULT HIGH
        # self.hiEntry.delete(0,END)
        # self.hiEntry.insert(0, MAXPOS)

        self.stepEntry = Entry(self.fr, width=20, bd=3, justify='right',
                               bg=inputbox, fg=statuscolor)
        self.stepEntry.grid(row=9, column=2, sticky='we')  # , columnspan=2)

        # put buttons for  GOTO and MOVE
        self.butGotoLow = Button(self.fr, text="Go To Low",
                                 justify='center', bg=buttoncolor, command=self.gotoLow)
        self.butGotoLow.grid(row=10, column=0, sticky='we')

        self.butGotoHi = Button(self.fr, text="Go To High",
                                justify='center', bg=buttoncolor, command=self.gotoHi)
        self.butGotoHi.grid(row=10, column=1, sticky='we')

        self.butMoveStep = Button(self.fr, text="Move a Step",
                                  justify='center', bg=buttoncolor, command=self.moveStep)
        self.butMoveStep.grid(row=10, column=2, sticky='we')

        self.emptyRow(11)

        Label(self.fr, text='EXTERNAL SENSORS', justify='left',
              anchor='w', bg=bgcolor, fg=statuscolor, font=("Calibri", 12)
              ).grid(row=12, column=0, columnspan=3, sticky='we', padx=(5, 0))

        # function buttons


        # RIadok 12: Externals
        butIFM = Button(self.fr, text="Read IFM", width=15, justify='center',
                        bg=buttoncolor, command=self.getIfm)  # self.exit_root)
        butIFM.grid(row=13, column=0, sticky='we')

        self.labIfmStatus = Label(self.fr, textvariable=self.ifmStatus,
                                  justify='left', anchor='w', bg=bgcolor, fg=statuscolor,
                                  font=("Calibri", 12))
        self.labIfmStatus.grid(row=13, column=1, columnspan=2,
                               sticky='we', padx=(15, 0))
        self.labIfmStatus.bind('<Button-1>', self.resetIfmStatus)

        butLVL = Button(self.fr, text="Read level", width=15, justify='center',
                        bg=buttoncolor, command=self.getLevel)  # self.exit_root)
        butLVL.grid(row=14, column=0, sticky='we')

        self.labLvlStatus = Label(self.fr, textvariable=self.lvlStatus,
                                  justify='left', anchor='w', bg=bgcolor, fg=statuscolor,
                                  font=("Calibri", 12))
        self.labLvlStatus.grid(row=14, column=1, columnspan=2,
                               sticky='we', padx=(15, 0))
        self.labLvlStatus.bind('<Button-1>', self.resetLvlStatus)

        self.emptyRow(15)

        Label(self.fr, text='OBSERVER:', anchor='w', justify='left',
              bg=bgcolor, fg=statuscolor, font=("Calibri", 12)
              ).grid(row=16, column=0, sticky='we', padx=(5, 0))
        self.entryObserver = Entry(self.fr, textvariable=self.observer,
                                   bg=inputbox, fg=statuscolor, font=("Calibri", 12),
                                   justify='left')
        self.entryObserver.grid(row=16, column=1, columnspan=2, sticky='we')

        # row 18> empty (or test connection)
        self.emptyRow(18)
        self.timeLabel = Label(self.fr, textvariable=self.timestring,
                               anchor='w', bg=bgcolor, fg=statuscolor,
                               font=("Calibri", 9))
        self.timeLabel.grid(row=19, column=0)

        self.connLabel = Label(self.fr, textvariable=self.connstring,
                               anchor='w', bg=bgcolor, fg=statuscolor,
                               font=("Calibri", 9))
        self.connLabel.grid(row=19, column=1)

        butexit = Button(self.fr, text="EXIT", width=15, justify='center',
                         bg="black", fg="yellow", command=self.close,
                         font=("Calibri", 14, "bold"))
        butexit.grid(row=19, column=2)
示例#15
0
class StreamFrame:
    def __init__(self, stream: Stream, parent, scrollWindow, searchFrame,
                 color):
        self.frame = Frame(scrollWindow,
                           relief=GROOVE,
                           highlightbackground=color,
                           highlightcolor=color,
                           highlightthickness=3)
        self.stream = stream
        self.parent = parent
        self.searchFrame = searchFrame

        self.previewFrame = Frame(self.frame, width=322, height=182)
        self.previewFrame.grid_propagate(False)
        self.boxFrame = Frame(self.frame)
        self.boxArtFrame = Frame(self.boxFrame)
        self.boxArtLabelFrame = Frame(self.boxFrame)
        self.filterFrame = Frame(self.frame)

        self.labelImage = None
        self.labelBoxArt = None
        self.buttonFilterGame = None
        self.buttonFilterStreamer = None
        self.buttonFilterCombined = None

        self.previewTitle = StringVar()
        self.previewImage = None
        self.boxArtImage = None
        self.previewName = StringVar()
        self.previewViewers = StringVar()

        self.setStringVars()
        self.addPreview()
        self.addFilterFrame()
        self.gridFrames()

    def gridFrames(self):
        self.previewFrame.grid(row=0, sticky=NSEW)
        self.boxFrame.grid(row=1, sticky=NSEW)
        self.boxArtFrame.grid(row=0, column=0, sticky=NSEW)
        self.boxArtLabelFrame.grid(row=0, column=1, sticky=W)
        self.filterFrame.grid(row=2, sticky=NSEW)

    def setStream(self, stream):
        self.stream = stream
        self.setStringVars()

    def setStringVars(self):
        self.previewTitle.set(
            self.stream.streamTitle.encode("ascii", "ignore").decode())
        self.boxArtImage = self.stream.DEFAULT_BOX_ART
        self.previewImage = self.stream.DEFAULT_STREAM_PREVIEW
        self.previewName.set(self.stream.stylizedStreamName)
        self.previewViewers.set(self.stream.viewerCount +
                                LabelConstants.VIEWERS)

    def addPreview(self):
        self.labelImage = Label(self.previewFrame,
                                image=self.previewImage,
                                bd=1)
        self.labelImage.bind(MiscConstants.BIND_LEFT_MOUSE,
                             lambda x: self.onClick(None))
        self.labelImage.grid(row=1, sticky=W)
        dummyImageToMakeLabelHaveWidthInPixels = PhotoImage(width=1, height=1)
        dummyLabelToGetWidthOfText = Label(None,
                                           textvariable=self.previewTitle)
        titleWidth = min(dummyLabelToGetWidthOfText.winfo_reqwidth() - 4, 308)
        labelTitle = Label(self.previewFrame,
                           image=dummyImageToMakeLabelHaveWidthInPixels,
                           textvariable=self.previewTitle,
                           fg="white",
                           bg="black",
                           compound=RIGHT,
                           anchor=W,
                           width=titleWidth)
        labelTitle.bind(MiscConstants.BIND_LEFT_MOUSE,
                        lambda x: self.onClick(None))
        labelTitle.grid(row=1, sticky=NW, padx=4, pady=4)
        self.labelBoxArt = Label(self.previewFrame,
                                 image=self.boxArtImage,
                                 bd=1)
        self.labelBoxArt.bind(MiscConstants.BIND_LEFT_MOUSE,
                              lambda x: self.onClick(None))
        self.labelBoxArt.grid(row=1, column=0, sticky=SW, padx=4, pady=4)
        labelName = Label(self.previewFrame,
                          textvariable=self.previewName,
                          fg="white",
                          bg="#b71ef7")
        labelName.bind(MiscConstants.BIND_LEFT_MOUSE,
                       lambda x: self.onClick(None))
        labelName.grid(row=1, sticky=S, padx=4, pady=4)
        labelViewers = Label(self.previewFrame,
                             textvariable=self.previewViewers,
                             fg="white",
                             bg="black")
        labelViewers.bind(MiscConstants.BIND_LEFT_MOUSE,
                          lambda x: self.onClick(None))
        labelViewers.grid(row=1, sticky=SE, padx=4, pady=4)

    def addFilterFrame(self):
        labelFilter = Label(self.filterFrame,
                            text=LabelConstants.FILTER,
                            anchor=W)
        labelFilter.grid(row=0, column=0, sticky=NSEW, padx=(4, 2))
        self.buttonFilterStreamer = Button(
            self.filterFrame,
            text=LabelConstants.FILTER_STREAMER,
            width=10,
            command=lambda: self.parent.addFilter(
                self.stream.stylizedStreamName, None))
        self.buttonFilterStreamer.grid(row=0,
                                       column=1,
                                       sticky=NSEW,
                                       padx=(2, 4),
                                       pady=(0, 4))
        self.buttonFilterGame = Button(
            self.filterFrame,
            text=LabelConstants.FILTER_GAME,
            width=10,
            command=lambda: self.parent.addFilter(None, self.stream.gameTitle))
        self.buttonFilterGame.grid(row=0,
                                   column=2,
                                   sticky=NSEW,
                                   padx=4,
                                   pady=(0, 4))
        self.buttonFilterCombined = Button(
            self.filterFrame,
            text=LabelConstants.FILTER_COMBO,
            width=13,
            command=lambda: self.parent.addFilter(
                self.stream.stylizedStreamName, self.stream.gameTitle))
        self.buttonFilterCombined.grid(row=0,
                                       column=3,
                                       sticky=NSEW,
                                       padx=(4, 0),
                                       pady=(0, 4))

    def onClick(self, event):
        if self.frame.cget("highlightbackground") == "red":
            self.frame.config(highlightbackground="grey",
                              highlightcolor="grey")
            idx = self.searchFrame.selectedStreamsListbox.get(0, END).index(
                self.stream.streamName)
            self.searchFrame.selectedStreamsListbox.delete(idx)
        else:
            self.frame.config(highlightbackground="red", highlightcolor="red")
            self.searchFrame.selectedStreamsListbox.insert(
                END, self.stream.streamName)
示例#16
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

__author__ = 'ipetrash'

from tkinter import Tk, Label


def turn(event):
    value = event.widget["text"]
    value = 1 if value == '.' else int(value) + 1

    event.widget["text"] = value


root = Tk()

for x in range(8):
    for y in range(8):
        cell = Label(root, width=3, height=1, text=".")
        cell.grid(row=x, column=y)
        cell.bind("<Button-1>", turn)

root.mainloop()
示例#17
0
class YEPT_window():

    def __init__(self):
        self.root = Tk()
        self.root.resizable(width = False, height = True)
        self._add_icon()
        self.layout()
    
    def layout(self):
        self._layout_main()
        self._layout_blast()
        canvas = Canvas(self.total, width = 14, height = 150)
        canvas.create_line(10, 0, 10, 150, fill = "#D8D8D8", width = 2)
        canvas.pack(after = self.blast, side = LEFT)
        self._layout_primerDesign()
        self.b2 = Button(self.frmbt, 
                         text = 'Get Checking Primers', 
                         font = ("Arial", 12))
        self.b2.bind("<Button-1>", self.openCheckPrimerWindow)
        self._layout_bottom()

    def _add_icon(self):
        self.root.iconbitmap(_iconPath)
    
    def _layout_main(self):
        self.root.title("YEPT - SLST,ShanghaiTech")
        # Up center banner
        l = Label(self.root, 
                  text="Welcome to YEPT!", 
                  font = ("Arial", 13), 
                  width = 15, height = 2)
        l.pack()

        # Main frame
        self.total = Frame(self.root)
        self.total.pack(fill = X)

    def _layout_blast(self):
        # Frame at the left side
        self.blast = Frame(self.total)
        self.blast.pack(pady = 5, padx = 8, side = LEFT)
        
        self.btf = Frame(self.blast)
        self.btf.pack(pady=5,fill=X)
        
        btitle = Label(self.btf, 
                       text = 'BLAST to get AccessionID', 
                       font = ("Arial", 10), width = 19)
        btitle.pack(side = RIGHT)
        
        self.lblast = Label(self.btf, 
                            text = "(Don't like it? Do it yourself.)", 
                            font = ("Arial", 9), fg = 'blue', width = 22)
        self.lblast.bind('<Enter>', self._blast_showlink)
        self.lblast.bind('<Leave>', self._blast_notshowlink)
        self.lblast.bind('<Button-1>', self._blast_gotoBLAST)
        self.lblast.pack(side = RIGHT, padx = 5)

        self._layout_blast_line1()
        self._layout_blast_line2()

        self.tb = Text(self.blast, width = 65, height = 6)
        self.tb.pack(pady = 5, side = RIGHT)

    def _layout_blast_line1(self):
        # BLAST species selection
        b_species = Frame(self.blast)
        b_species.pack(pady = 5, fill = X)
        
        bspl = Label(b_species, 
                     text = "Target pecies:", 
                     font = ("Arial", 10), width = 10)
        self.bsp_var = StringVar()
        self.bsp_var.set(5)
        bIssj = Radiobutton(b_species, 
                            text = "S. japonicus", 
                            variable = self.bsp_var, value = "J")
        bIssj.bind("<Button-1>", self._focusB)
        bIssc = Radiobutton(b_species, 
                            text = "S. cryophilus", 
                            variable = self.bsp_var, value = "C")
        bIssc.bind("<Button-1>", self._focusB)
        bIsso = Radiobutton(b_species, 
                            text = "S. octosporus", 
                            variable = self.bsp_var, value = "O")
        bIsso.bind("<Button-1>", self._focusB)
        bIsso.pack(side = RIGHT)
        bIssc.pack(side = RIGHT)
        bIssj.pack(side = RIGHT)
        bspl.pack(side = RIGHT)
    
    def _layout_blast_line2(self):
        # Gene name entry line
        sp_name = Frame(self.blast)
        sp_name.pack(pady = 5, fill = X)
        
        sp_name_l = Label(sp_name, 
                          text = 'Gene in S. pombe:', 
                          font = ("Arial", 10), width = 13)
        sp_name_l.pack(side = RIGHT)        
        self.sp_name_e = Entry(sp_name, width = 6)
        self.sp_name_e.bind("<Button-1>", self._focusB)
        self.sp_name_e.bind("<Return>", self._BLAST)
        self.sp_name_e.bind("<Key>", self._forgetb2)
        self.sp_name_e.pack(side = RIGHT, padx = 5, before = sp_name_l)

        cov_l = Label(sp_name, 
                      text = 'Cov cutoff:', font = ("Arial", 10), width = 7)
        cov_l.pack(side = RIGHT, before = self.sp_name_e)
        self.cov_cutoff = Entry(sp_name, width = 4)
        self.cov_cutoff.insert(END, '0.15')
        self.cov_cutoff.bind("<Button-1>", self._focusB)
        self.cov_cutoff.bind("<Return>", self._BLAST)
        self.cov_cutoff.bind("<Key>", self._forgetb2)
        self.cov_cutoff.pack(side = RIGHT, padx = 5, before = cov_l)

        ev_l = Label(sp_name, 
                     text = 'evalue cutoff:', font = ("Arial", 10), width = 10)
        ev_l.pack(side = RIGHT, before = self.cov_cutoff)
        self.ev_cutoff = Entry(sp_name, width = 3)
        self.ev_cutoff.insert(END, '1')
        self.ev_cutoff.bind("<Button-1>", self._focusB)
        self.ev_cutoff.bind("<Return>", self._BLAST)
        self.ev_cutoff.bind("<Key>", self._forgetb2) 
        self.ev_cutoff.pack(side = RIGHT, padx = 5, before = ev_l)
        
        self.button_blast = Button(sp_name, text = 'BLAST', 
                                   font = ("Arial", 9))
        self.button_blast.bind('<Button-1>', self._BLAST)
        self.button_blast.bind('<Return>', self._BLAST)
        self.button_blast.pack(side = RIGHT, before = self.ev_cutoff)

    def _blast_showlink(self, event):
        self.lblast.config(bg = "#D8D8D8")
    
    def _blast_notshowlink(self, event):
        self.lblast.forget()
        self.lblast = Label(self.btf, 
                            text = "(Don't like it? Do it yourself.)", 
                            font = ("Arial", 9), fg = 'blue', width = 22)
        self.lblast.bind('<Enter>', self._blast_showlink)
        self.lblast.bind('<Leave>', self._blast_notshowlink)
        self.lblast.bind('<Button-1>', self._blast_gotoBLAST)
        self.lblast.pack(side=RIGHT,padx=5)
    
    def _blast_gotoBLAST(self, event):
        BLASTn_url = "http://blast.ncbi.nlm.nih.gov/Blast.cgi?PROGRAM=blastn&PAGE_TYPE=BlastSearch&LINK_LOC=blasthome"
        webopen(BLASTn_url, new = 2, autoraise = True)

    def _BLAST(self, event):
        self.tb.delete(0.0,END)
        gene_name = self.sp_name_e.get()
        species = self.bsp_var.get()
        ev_cutoff = float(self.ev_cutoff.get())
        cov_cutoff = float(self.cov_cutoff.get())

        if species == '5':
            self.tb.delete(0.0, END)
            self.tb.insert(END, 'Please choose a target species.')
        elif gene_name == '':
            self.tb.delete(0.0, END)
            self.tb.insert(END, 'Please enter a gene identifier.')
        else:
            output = BLAST_by_sp(gene_name, species, cov_cutoff, ev_cutoff)
            self.tb.delete(0.0, END)
            if output == []:
                self.tb.delete(0.0, END)
                self.tb.insert(END, 'No significant hit found.')
            elif output == 'NoName':
                self.tb.delete(0.0, END)
                self.tb.insert(END, 'There is no gene called "%s" in S. pombe.' % gene_name)
                self.tb.insert(END, str(output))
            else:
                self.tb.delete(0.0, END)
                for hit in output:
                    msg = "E-value: {}\tCov%: {:.2f}\tIdent%: {:.2f}\n".format(hit[0], hit[1], hit[2])
                    for cds in hit[3:]:
                        msg += '\t'.join(cds) + '\n'
                    self.tb.insert(END, msg)

    def _layout_primerDesign(self):
        self.options = Frame(self.total)
        self.options.pack(pady = 5, padx = 10, side = RIGHT)

        self.entries = Frame(self.options)
        self.entries.pack(fill = X, pady = 5)
        
        self._layout_primerDesign_line1()
        self._layout_primerDesign_line2()
        self._layout_primerDesign_line3()
        self._layout_primerDesign_line4_1()
        self._layout_primerDesign_line4_2()
        
        self.frmbt = Frame(self.options)
        self.frmbt.pack(pady = 5, fill = X, side = BOTTOM)
        
        self.b1 = Button(self.frmbt, text = 'Get Primer', font = ("Arial", 12))
        self.b1.bind("<Return>", self.getPrimer)
        self.b1.bind("<Button-1>", self.getPrimer)
        self.b1.pack(side = LEFT, pady = 5, ipady = 1, ipadx = 1)
        
        self.b2 = Button(self.frmbt, 
                         text = 'Get Checking Primers', 
                         font = ("Arial", 12))
        self.b2.bind("<Button-1>", self.openCheckPrimerWindow)

    def _layout_bottom(self):

        primer_result = Frame(self.root)
        primer_result.pack(pady = 5)

        rtf = Frame(primer_result) # result title frame
        rtf.pack(fill = X)
        
        result_title = Label(rtf, 
                             text = 'The primer we get is following:', 
                             font = ("Arial", 11))
        result_title.pack(side = LEFT)

        rcf = Frame(primer_result) # result content frame
        rcf.pack(fill = X)
        
        self.t = Text(rcf, width = 125, height = 5)
        self.t.pack(side = LEFT, fill = Y, expand = YES)
        
        scr = Scrollbar(rcf)
        scr.pack(side = RIGHT, fill = Y)
        self.t["yscrollcommand"] = scr.set
        scr['command'] = self.t.yview

    def _layout_primerDesign_line1(self):
        l2 = Label(self.entries, 
                   text = 'Accession ID for all or \ngene symbol in S. pombe:', 
                   font = ("Arial", 10), width = 20)
        l2.pack(side = LEFT)
        
        self.e2 = Entry(self.entries, width = 14)
        self.e2.bind("<Return>", self.getPrimer)
        self.e2.bind("<Key>", self._forgetb2)
        self.e2.pack(side = LEFT)
        
        l3 = Label(self.entries, text = 'length:',
                   font = ("Arial", 10), width = 6)
        l3.pack(side = LEFT)
        
        self.e3 = Entry(self.entries, width = 3)
        self.e3.insert(0, '80')
        self.e3.bind("<Return>", self.getPrimer)
        self.e3.bind("<Key>", self._forgetb2)
        self.e3.pack(side = LEFT)

    def _layout_primerDesign_line2(self):
        check_species = Frame(self.options)
        check_species.pack(fill = X, pady = 5)
        
        sp = Label(check_species, text = 'Species:', 
                   font = ("Arial", 10), width = 6)
        sp.pack(side = LEFT)
        
        self.species_var = StringVar()
        self.species_var.set(1)
        Issp = Radiobutton(check_species, text = "S. pombe", 
                           variable = self.species_var, value = "P")
        Issp.bind("<Button-1>", self._getfocusback)
        Issp.pack(side = LEFT)
        Issj = Radiobutton(check_species, text = "S. japonicus", 
                           variable=self.species_var, value = "J")
        Issj.bind("<Button-1>", self._getfocusback)
        Issj.pack(side = LEFT)
        Issc = Radiobutton(check_species, text = "S. cryophilus", 
                           variable = self.species_var, value = "C")
        Issc.bind("<Button-1>", self._getfocusback)
        Issc.pack(side = LEFT)
        Isso = Radiobutton(check_species, text = "S. octosporus", 
                           variable = self.species_var, value = "O")
        Isso.bind("<Button-1>", self._getfocusback)
        Isso.pack(side = LEFT)

    def _layout_primerDesign_line3(self):
        self.check_mode = Frame(self.options)
        self.check_mode.pack(fill = X, pady = 5)
        
        self.mode_var = StringVar()
        self.mode_var.set(2)
        md = Label(self.check_mode, text = 'Fuction:', 
                   font = ("Arial", 10), width = 6)
        md.pack(side = LEFT)
        Isdel = Radiobutton(self.check_mode,text = "Deletion", 
                            variable = self.mode_var, value="del", 
                            command = self._choose_plasmid)
        Isdel.bind("<Button-1>", self._getfocusback)
        Isdel.pack(side = LEFT)
        IsC = Radiobutton(self.check_mode, text = "C-terminal Tagging", 
                          variable = self.mode_var, value = "C", 
                          command = self._choose_Ctag)
        IsC.bind("<Button-1>", self._getfocusback)
        IsC.pack(side = LEFT)
        IsN = Radiobutton(self.check_mode, text = "N-terminal promoter adding", 
                          variable = self.mode_var, value = "N", 
                          command = self._choose_Ntag)
        IsN.bind("<Button-1>", self._getfocusback)
        IsN.pack(side = LEFT)

    def _layout_primerDesign_line4_1(self):
        self.blankframe = Frame(self.options)
        self.blankframe.pack(after = self.check_mode, pady = 18)
        
        self.check_plsmd = Frame(self.options)
        self.check_plsmd.pack(after = self.check_mode, pady = 5)
        self.check_plsmd.forget()
        
        pl = Label(self.check_plsmd, text = 'Plasmid:', 
                   font = ("Arial", 10), width = 10)
        pl.pack(side = LEFT)
        self.plasmid_var = StringVar()
        self.plasmid_var.set(3)
        IspFA6a = Radiobutton(self.check_plsmd, text = "pFA6a", 
                              variable = self.plasmid_var, value = 'pFA6a')
        IspFA6a.bind("<Button-1>", self._getfocusback)
        IspFA6a.pack(side = LEFT)
        IsKS = Radiobutton(self.check_plsmd, text = "KS-ura4", 
                           variable = self.plasmid_var, value = 'KS-ura4')
        IsKS.bind("<Button-1>", self._getfocusback)
        IsKS.pack(side = LEFT)

    def _layout_primerDesign_line4_2(self):
        self.check_Ntag = Frame(self.options)
        self.check_Ntag.pack(after = self.check_mode, pady = 5)
        self.check_Ntag.forget()
        
        nt = Label(self.check_Ntag, text = 'N-terminal Tag:', 
                   font = ("Arial", 10), width = 10)
        nt.pack(side = LEFT)
        
        self.Ntag_var = StringVar()
        self.Ntag_var.set(' ')
        Isnone = Radiobutton(self.check_Ntag, text = "None", 
                           variable = self.Ntag_var, value = ' ')
        Isnone.bind("<Button-1>", self._getfocusback)
        Isnone.pack(side=LEFT)
        Is3HA = Radiobutton(self.check_Ntag, text = "3HA", 
                          variable = self.Ntag_var, value = '3HA')
        Is3HA.bind("<Button-1>", self._getfocusback)
        Is3HA.pack(side = LEFT)
        IsGST = Radiobutton(self.check_Ntag, text = "GST", 
                          variable = self.Ntag_var, value = 'GST')
        IsGST.bind("<Button-1>", self._getfocusback)
        IsGST.pack(side = LEFT)
        IsGFP = Radiobutton(self.check_Ntag, text = "GFP", 
                            variable = self.Ntag_var, value = 'GFP')
        IsGFP.bind("<Button-1>", self._getfocusback)
        IsGFP.pack(side = LEFT)

    def _choose_Ntag(self):
        self.blankframe.forget()
        self.check_plsmd.forget()
        self.check_Ntag.pack(after = self.check_mode, pady = 5)

    def _choose_plasmid(self):
        self.blankframe.forget()
        self.check_Ntag.forget()
        self.check_plsmd.pack(after = self.check_mode, pady = 5)

    def _choose_Ctag(self):
        self.blankframe.pack(pady = 18)
        self.check_Ntag.forget()
        self.check_plsmd.forget()

    def _noResultMsg(self, keyword, species):
        self.t.delete(0.0, END)
        self.t.insert(END, 
            "No gene matches \"{}\" in {}.".format(keyword, species))

    def _ambResultMsg(self, keyword, species, results):
        self.t.delete(0.0, END)
        nResult, dfRepr = formatMultiResult(results)
        self.t.insert(END, 
            "{0} entries found to match \"{1}\" in {2}:\n{3}".format(nResult, keyword, species, dfRepr))

    def getPrimer(self, event):
        self.b1.focus_set()
        mode = self.mode_var.get()
        species = self.species_var.get()
        gene = self.e2.get()
        plasmid = self.plasmid_var.get()

        if mode != 'del':
            plasmid = 'pFA6a'

        if species == "1" or mode == "2" or plasmid == "3":
            self.t.delete(0.0, END)
            self.t.insert(END, "Please check all the radiobutton needed!\n")
        else:
            fullSpeciesNameMap = {'P': 'S. pombe', 'J': 'S. japonicus', 
                            'C': 'S. cryophilus', 'O': 'S. octosporus'}
            fullSpeciesName = fullSpeciesNameMap[species]
            
            Ntag = self.Ntag_var.get()
            length = int(self.e3.get())
            
            if plasmid == "pFA6a":
                forward_plmd_del = "CGGATCCCCGGGTTAATTAA"
                reverse_plmd_del = "GAATTCGAGCTCGTTTAAAC"
                forward_plmd_N = "GAATTCGAGCTCGTTTAAAC"
                reverse_plmd_N = "CATGATTTAACAAAGCGACTATA"
                reverse_plmd_N_3HA = "GCACTGAGCAGCGTAATCTG"
                reverse_plmd_N_GST = "ACGCGGAACCAGATCCGATT"
                reverse_plmd_N_GFP = "TTTGTATAGTTCATCCATGC"
            elif plasmid == "KS-ura4":
                forward_plmd_del = "CGCCAGGGTTTTCCCAGTCACGAC"
                reverse_plmd_del = "AGCGGATAACAATTTCACACAGGA"

            if mode == 'del':
                primer = get_del_primer(species, gene, length)
                if primer == []:
                    self._noResultMsg(gene, fullSpeciesName)
                elif type(primer) == list and len(primer) > 1:
                    self._ambResultMsg(gene, fullSpeciesName, primer)
                else:
                    self.t.delete(0.0, END)
                    self.t.insert(END, 'Found gene: {}, GenBank: {}, systematic ID: {}\n'.format(primer[2][0], primer[2][1], primer[2][2]))
                    self.t.insert(END, 'Forward primer: {} - {}\n'.format(primer[0], forward_plmd_del))
                    self.t.insert(END, '                %GC content = {} TM = {}\n'.format(GC(primer[0] + forward_plmd_del), TM(primer[0] + forward_plmd_del)))
                    self.t.insert(END, 'Reverse primer: {} - {}\n'.format(primer[1], reverse_plmd_del))
                    self.t.insert(END, '                %GC content = {} TM = {}'.format(GC(primer[1] + reverse_plmd_del), TM(primer[1] + reverse_plmd_del)))
                    self.b2.pack(side = LEFT, pady = 5, padx = 7, ipady = 1, ipadx = 1)
                    self.b2.focus_set()
            elif mode == 'C':
                primer = get_Ctag_primer(species, gene, length)
                if primer == []:
                    self._noResultMsg(gene, fullSpeciesName)
                elif type(primer) == list and len(primer) > 1:
                    self._ambResultMsg(gene, fullSpeciesName, primer)
                else:
                    self.t.delete(0.0, END)
                    self.t.insert(END, 'Found gene: {}, GenBank: {}, systematic ID: {}\n'.format(primer[2][0], primer[2][1], primer[2][2]))
                    self.t.insert(END, 'Forward primer: {} - {}\n'.format(primer[0], forward_plmd_del))
                    self.t.insert(END, '                %GC content = {} TM = {}\n'.format(GC(primer[0] + forward_plmd_del), TM(primer[0] + forward_plmd_del)))
                    self.t.insert(END, 'Reverse primer: {} - {}\n'.format(primer[1], reverse_plmd_del))
                    self.t.insert(END, '                %GC content = {} TM = {}'.format(GC(primer[1] + reverse_plmd_del), TM(primer[1] + reverse_plmd_del)))
                    self.b2.pack(side = LEFT, pady = 5, padx = 7, ipady = 1, ipadx = 1)
                    self.b2.focus_set()
            elif mode == 'N':
                if Ntag == ' ':
                    primer = get_Ntag_none_primer(species, gene,length)
                else:
                    primer = get_Ntag_tag_primer(species, gene,length)
                    if Ntag == "3HA":
                        reverse_plmd_N = reverse_plmd_N_3HA
                    elif Ntag == "GST":
                        reverse_plmd_N = reverse_plmd_N_GST
                    elif Ntag == "GFP":
                        reverse_plmd_N = reverse_plmd_N_GFP
                if primer == []:
                    self._noResultMsg(gene, fullSpeciesName)
                elif type(primer) == list and len(primer) > 1:
                    self._ambResultMsg(gene, fullSpeciesName, primer)
                else:
                    self.t.delete(0.0, END)
                    self.t.insert(END, 'Found gene: {}, GenBank: {}, systematic ID: {}\n'.format(primer[2][0], primer[2][1], primer[2][2]))
                    self.t.insert(END, 'Forward primer: {} - {}\n'.format(primer[0], forward_plmd_N))
                    self.t.insert(END, '                %GC content = {} TM = {}\n'.format(GC(primer[0] + forward_plmd_N), TM(primer[0] + forward_plmd_N)))
                    self.t.insert(END, 'Reverse primer: {} - {}\n'.format(primer[1], reverse_plmd_N))
                    self.t.insert(END, '                %GC content = {} TM = {}'.format(GC(primer[1] + reverse_plmd_N), TM(primer[1] + reverse_plmd_N)))
                    self.b2.pack(side = LEFT, pady = 5, padx = 7, ipady = 1, ipadx = 1)
                    self.b2.focus_set()

    def _backtob3(self, event):
        self.b3.focus_set()

    def _focusB(self, event):
        self.button_blast.focus_set()

    def _getfocusback(self, event):
        self.b1.focus_set()
        self.b2.forget()

    def _forgetb2(self, event):
        self.b2.forget()

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

    def openCheckPrimerWindow(self, event):
        CheckPrimerWindow(self)
示例#18
0
labelCodeInfo = Label(frame,
                      text='Click on a code to\n copy it to the clipboard!',
                      fg=color_sec,
                      width=50)
labelCodeInfo.configure(background=color_wbg, font=font_prim)
labelCodeInfo.pack()

labelInfo = Label(frame, text='\nShiftCodes are parsed from')
labelInfo.configure(background=color_wbg, fg=color_fg, font=font_prim)
labelInfo.pack()

link0 = Label(frame, text="orcz.com : Borderlands 1", cursor="target")
link0.configure(background=color_wbg, fg=color_sec, font=font_prim)
link0.pack()
link0.bind("<Button-1>", lambda e: callback(url_b1))

link1 = Label(frame, text="orcz.com : Borderlands 2", cursor="target")
link1.configure(background=color_wbg, fg=color_sec, font=font_prim)
link1.pack()
link1.bind("<Button-1>", lambda e: callback(url_b2))

link2 = Label(frame,
              text="orcz.com : Borderlands - Pre Sequel",
              cursor="target")
link2.configure(background=color_wbg, fg=color_sec, font=font_prim)
link2.pack()
link2.bind("<Button-1>", lambda e: callback(url_bps))

link3 = Label(frame, text="orcz.com : Borderlands 3", cursor="target")
link3.configure(background=color_wbg, fg=color_sec, font=font_prim)
示例#19
0
class DrowingApp:
    data, fileOpend, my_point, x, y = {}, "", 0, 0, 0

    #Constructor __init__
    def __init__(self, master, WIDTH=1100, HEIGHT=800):
        master.title("GUI HW2 By Shani & Idan & mhmd ")
        self.my_color = "Black"
        self.create_canvas(master, WIDTH, HEIGHT)
        master.attributes("-transparentcolor", "red")
        self.create_upper_menu()
        # lower section
        self.lower_frame = Canvas(self.master, bg='#c9daf8', bd=5)
        self.lower_frame.place(relx=0.5,
                               rely=0.25,
                               relwidth=0.75,
                               relheight=0.6,
                               anchor='n')
        self.lower_frame.bind("<ButtonPress-1>", self.moveEvent)
        self.reset()

    # resize image by canvas size
    def resizeimage(self, event):
        image = self.image_copy.resize(
            (self.master.winfo_width(), self.master.winfo_height()))
        self.image1 = ImageTk.PhotoImage(image)
        self.label.config(image=self.image1)

    def loadbackground(self):
        self.label = Label(self.canvas, image=self.background)
        self.label.bind('<Configure>', self.resizeimage)
        self.label.pack(fill='both', expand='yes')

    def rootgeometry(self, WIDTH, HEIGHT):
        self.master.geometry(str(WIDTH) + 'x' + str(HEIGHT))

    #Create Ship from data get from file
    def createShip(self, lines, circels, bezier):
        #Process work simultany
        thread_list = []
        for line in lines:
            thread = threading.Thread(target=self.myLine,
                                      args=(line[0], line[1], line[2],
                                            line[3]))
            thread_list.append(thread)
        for circle in circels:
            thread = threading.Thread(target=self.myCircle,
                                      args=(circle[0], circle[1], circle[2],
                                            circle[3]))
            thread_list.append(thread)
        thread = threading.Thread(target=self.myCurve,
                                  args=(bezier[0], bezier[1], bezier[2],
                                        bezier[3], bezier[4], bezier[5],
                                        bezier[6], bezier[7]))
        thread_list.append(thread)
        for thread in thread_list:
            thread.start()

    def create_upper_menu(self):
        # Uper section 1
        frame = Frame(self.master, bg='#a0dbd1', bd=4)
        frame.place(relx=0.5,
                    rely=0.04,
                    relwidth=0.80,
                    relheight=0.1,
                    anchor='n')
        # Open jason file
        openfile = TkinterCustomButton(master=frame,
                                       height=52,
                                       text="Open File",
                                       command=self.openfile)
        openfile.place(relx=0)
        # Derivative
        derivative = TkinterCustomButton(master=frame,
                                         height=52,
                                         text="cutting",
                                         command=self.derived)
        derivative.place(relx=0.20)
        # Reset by defult/user file if he upload file
        reset = TkinterCustomButton(master=frame,
                                    height=52,
                                    text="Reset",
                                    command=self.reset)
        reset.place(relx=0.40)
        # Help give the option to open help file to get all information abount function
        helps = TkinterCustomButton(master=frame,
                                    height=52,
                                    text="Help",
                                    command=self.helpf)
        helps.place(relx=0.60)
        rotate = TkinterCustomButton(master=frame,
                                     height=52,
                                     text="rotate",
                                     command=self.rotate)
        rotate.place(relx=0.80)

        # Uper section 2
        frame2 = Frame(self.master, bg='#a0dbd1', bd=4)
        frame2.place(relx=0.5,
                     rely=0.15,
                     relwidth=0.8,
                     relheight=0.1,
                     anchor='n')
        # Move to current position
        move = TkinterCustomButton(master=frame2,
                                   height=52,
                                   text="Move",
                                   command=self.move)
        move.place(relx=0)
        # zoomIn
        zoomIn = TkinterCustomButton(master=frame2,
                                     height=52,
                                     text="zoomIn +",
                                     command=self.zoomIn)
        zoomIn.place(relx=0)
        # zoomOut
        zoomOut = TkinterCustomButton(master=frame2,
                                      height=52,
                                      text="zoomOut -",
                                      command=self.zoomOut)
        zoomOut.place(relx=0.20)
        MirorX = TkinterCustomButton(master=frame2,
                                     height=52,
                                     text="Miror to X",
                                     command=self.mirrorX)
        MirorX.place(relx=0.40)
        MirorY = TkinterCustomButton(master=frame2,
                                     height=52,
                                     text="Miror to Y",
                                     command=self.mirrory)
        MirorY.place(relx=0.60)
        MirrorXY = TkinterCustomButton(master=frame2,
                                       height=52,
                                       text="Miror to XY",
                                       command=self.mirrorXY)
        MirrorXY.place(relx=0.80)

    # Open file if dont find any will drop massage
    def openfile(self):
        self.action = 'openfile'
        tf = filedialog.askopenfilename(initialdir="../Path/For/JSON_file",
                                        filetypes=((".json", "*.json"),
                                                   ("All Files", "*.*")),
                                        title="Choose a file.")
        try:
            if tf:
                with open(tf) as f:
                    self.data = json.load(f)
                    self.fileOpend = f
                self.createShip(self.data['lines'], self.data['circles'],
                                self.data['bezier'])
            elif tf == '':
                messagebox.showinfo("cencel", "file not selcted")
        except IOError:
            messagebox.showinfo("Error", "erorr")

    # Upload last file and create ship from screatch
    def reset(self):
        self.action = "reset"
        if self.fileOpend == "":
            with open('./ship.json') as f:
                self.data = json.load(f)
        else:
            with open(self.fileOpend) as f:
                self.lower_frame.delete("all")
                self.data = json.load(f)
        self.lower_frame.delete("all")
        self.createShip(self.data['lines'], self.data['circles'],
                        self.data['bezier'])

    # create_canvas with all atributes
    def create_canvas(self, master, WIDTH, HEIGHT):
        self.master = master
        self.rootgeometry(WIDTH, HEIGHT)
        self.canvas = Canvas(self.master)
        self.canvas.pack()
        self.background_image = Image.open('bg.PNG')
        self.image_copy = self.background_image.copy()
        self.background = ImageTk.PhotoImage(self.background_image)
        self.loadbackground()

    # Put pixel on gui by cordinat
    def putPixel(self, x_, y_):
        self.lower_frame.create_line(x_,
                                     y_,
                                     x_ + 1,
                                     y_ + 1,
                                     fill=self.my_color)

    # Bersenheim
    def myLine(self, x1, y1, x2, y2):
        #Bresenham's Line Algorithm
        # Determine how steep the line is
        direction = abs(y2 - y1) > abs(x2 - x1)
        if direction:
            x1, y1, x2, y2 = y1, x1, y2, x2
        if x1 > x2:
            x1, x2 = x2, x1
            y1, y2 = y2, y1
        # Recalculate differentials
        dx = x2 - x1
        dy = y2 - y1
        # Calculate error
        errp = 2 * dx
        direcx = 1 if x2 - x1 >= 0 else -1
        direcy = 1 if y2 - y1 >= 0 else -1
        # Iterate over bounding box generating points between start and end
        y, x = int(y1), int(x1)
        steps = int(max(dx, dy))
        for i in range(steps):
            self.putPixel(y, x) if direction else self.putPixel(x, y)
            errp -= 2 * abs(dy)
            if errp < 0:
                y += direcy
                errp += 2 * abs(dx)
            x += direcx

    # Plot Circle
    def plotCirclePoints(self, xc, yc, x, y):
        self.putPixel(xc + x, yc + y)
        self.putPixel(xc - x, yc + y)
        self.putPixel(xc + x, yc - y)
        self.putPixel(xc - x, yc - y)
        self.putPixel(xc + y, yc + x)
        self.putPixel(xc - y, yc + x)
        self.putPixel(xc + y, yc - x)
        self.putPixel(xc - y, yc - x)

    # Create Circle
    def myCircle(self, xc, yc, x2, y2):
        radius = math.sqrt((x2 - xc)**2 + (y2 - yc)**2)
        "Bresenham complete circle algorithm in Python"
        p = 3 - (2 * radius)
        x = 0
        y = radius
        while x < y:
            self.plotCirclePoints(xc, yc, x, y)
            if p < 0:
                p = p + (4 * x) + 6
            else:
                self.plotCirclePoints(xc, yc, x, y)
                p = p + (4 * (x - y)) + 10
                y -= 1
            x += 1
        if (x == y):
            self.plotCirclePoints(xc, yc, x, y)

    # bezier for cruve
    def bezier(self, x1, x2, x3, x4, t):
        ax = -x1 + 3 * x2 - 3 * x3 + x4
        bx = 3 * x1 - 6 * x2 + 3 * x3
        cx = -3 * x1 + 3 * x2
        dx = x1
        res = ax * t**3 + bx * t**2 + cx * t + dx
        return int(res)

    def myCurve(self, x1, y1, x2, y2, x3, y3, x4, y4):
        xt1 = x1
        yt1 = y1
        path_resolution = 1000
        for t in range(0, path_resolution + 1):
            pointx = self.bezier(x1, x2, x3, x4, t / path_resolution)
            pointy = self.bezier(y1, y2, y3, y4, t / path_resolution)
            self.myLine(xt1, yt1, pointx, pointy)
            xt1 = pointx
            yt1 = pointy
        return

    def zoomToFile(self, shape, zoom):
        if (zoom):
            for i in range(len(shape)):
                if i % 2 == 0:
                    shape[i] = int(1.1 * shape[i])
                else:
                    shape[i] = int(1.1 * shape[i])
        else:
            for i in range(len(shape)):
                if i % 2 == 0:
                    shape[i] = int(0.9 * shape[i])
                else:
                    shape[i] = int(0.9 * shape[i])

    # Help file
    def helpf(self):
        self.action = "helpf"
        os.system('help.pdf')

    def zoomIn(self):
        self.action = "zoomIn"
        self.lower_frame.delete("all")
        x, y = self.data["lines"][0][0], self.data["lines"][0][1]
        self.moveTo(0, 0)
        for line in self.data["lines"]:
            self.zoomToFile(line, 1)
        for circle in self.data["circles"]:
            self.zoomToFile(circle, 1)
        self.zoomToFile(self.data["bezier"], 1)
        self.createShip(self.data['lines'], self.data['circles'],
                        self.data['bezier'])
        self.moveTo(x, y)

    def zoomOut(self):
        self.action = "zoomOut"
        x, y = self.data["lines"][0][0], self.data["lines"][0][1]
        self.moveTo(0, 0)
        self.lower_frame.delete("all")
        for line in self.data["lines"]:
            self.zoomToFile(line, 0)
        for circle in self.data["circles"]:
            self.zoomToFile(circle, 0)
        self.zoomToFile(self.data["bezier"], 0)
        self.createShip(self.data['lines'], self.data['circles'],
                        self.data['bezier'])
        self.moveTo(x, y)

    def moveShape(self, shape, stepx, stepy):
        for i in range(len(shape)):
            if i % 2 == 0:
                shape[i] += stepx
            else:
                shape[i] += stepy

    def moveTo(self, x, y, move=0):
        if (self.action == 'move' or move):
            # Get first x,y
            self.x = x
            self.y = y
            #clear
            self.lower_frame.delete("all")
            #set new ship
            stepx = x - self.data["lines"][0][0]
            stepy = y - self.data["lines"][0][1]
            for line in self.data["lines"]:
                self.moveShape(line, stepx, stepy)
            for circle in self.data["circles"]:
                self.moveShape(circle, stepx, stepy)
            self.moveShape(self.data["bezier"], stepx, stepy)
            self.createShip(self.data['lines'], self.data['circles'],
                            self.data['bezier'])

    def moveEvent(self, event):
        self.moveTo(event.x, event.y)

    def move(self):
        #lisinigs for click
        self.action = 'move'

    def derivedShape(self, shape, derive):
        for i in range(len(shape)):
            if i % 2 == 0:
                shape[i] = shape[i] + shape[i + 1] * derive

    def derived(self):
        self.action = "derived"
        self.lower_frame.delete("all")
        for line in self.data["lines"]:
            self.derivedShape(line, 0.1)
        for circle in self.data["circles"]:
            self.derivedShape(circle, 0.1)
        self.derivedShape(self.data["bezier"], 0.1)
        self.createShip(self.data['lines'], self.data['circles'],
                        self.data['bezier'])

    def myMirror(self, shape, mirror):
        for i in range(len(shape)):
            if i % 2 == 0:
                [x, y,
                 d] = np.array([shape[i], shape[i + 1], 1]) * np.array(mirror)
                shape[i], shape[i + 1] = x[0], y[1]

    def mirrorfunc(self, mirrorP):

        self.lower_frame.delete("all")
        for line in self.data["lines"]:
            self.myMirror(line, mirrorP)
        for circle in self.data["circles"]:
            self.myMirror(circle, mirrorP)
        self.myMirror(self.data["bezier"], mirrorP)

    def mirrorXY(self):
        x, y = self.data["lines"][0][2], self.data["lines"][0][3]
        mirrorP = [[-1, 0, 0], [0, -1, 0], [0, 0, 1]]
        self.mirrorfunc(mirrorP)
        self.moveTo(x, y, 1)

    # rotation logic
    def mirrorX(self):
        x, y = self.data["lines"][0][0], self.data["lines"][0][1]
        mirrorP = [[1, 0, 0], [0, -1, 0], [0, 0, 1]]
        self.mirrorfunc(mirrorP)
        self.moveTo(x, y, 1)
        # rotation logic

    def mirrory(self):
        x, y = self.data["lines"][0][2], self.data["lines"][0][3]
        mirrorP = [[-1, 0, 0], [0, 1, 0], [0, 0, 1]]
        self.mirrorfunc(mirrorP)
        self.moveTo(x, y, 1)

    def rotateShape(self, shape, angle=45):
        for i in range(len(shape)):
            if i % 2 == 0:
                x, y = shape[i], shape[i + 1]
                shape[i] = int(x * cos(angle) - y * sin(angle))
                shape[i + 1] = int(y * cos(angle) + x * sin(angle))

    # rotate
    def rotate(self):
        self.action = 'rotate'
        self.lower_frame.delete("all")
        x, y = self.data["lines"][8][2], self.data["lines"][8][3]
        self.moveTo(0, 0)
        for line in self.data["lines"]:
            self.rotateShape(line)
        for circle in self.data["circles"]:
            self.rotateShape(circle)
        self.rotateShape(self.data["bezier"])
        self.moveTo(x, y, 1)
        self.createShip(self.data['lines'], self.data['circles'],
                        self.data['bezier'])
示例#20
0
class CalendarDay(Frame):
    def __init__(self,master=None, text='', fg='black', mode=0, cnf={}, **kw):
        Frame.__init__(self,master, cnf, **kw)
        self.mode = mode
        self._day_text=text
        self.double_clicked=False
        self.double_clicked_once=False
        self.active_logos=[]
        self.logolabels=[]
        self.active_color = 'whitesmoke'
        self.passive_color = 'lightgrey'

        self['background'] = self.passive_color       

        self.bind('<Button-1>', self.clicked_day)         # bind left mouse clicks
        self.bind('<Double-1>', self.double_clicked_day)  # bind double left clicks
        self.bind("<Enter>", self.on_enter)
        self.bind("<Leave>", self.on_leave)
            
        self.day_label=Label(self,text=self._day_text,background=self['background'],fg=fg,anchor='e')
        self.day_label.grid(column=0,row=0)
        self.day_label.bind('<Button-1>', self.clicked_day)
        self.day_label.bind('<Double-1>', self.double_clicked_day)

        if mode == 0:
            print('Mode = 0 (Logos where shown)')
            self.logo_frame=Frame(self,background=self['background'])
            self.logo_frame.grid(column=0,row=1)
      
            for i in range(Logos.MAX_ACTIVE_LOGOS):
                self.logolabels.append(Label(self.logo_frame, image='', width=1,height=1,background=self['background'],font=Fonts.mini))

            for column,logolabel in enumerate(self.logolabels):
                logolabel.grid(row=0,column=column,padx=1,pady=1,sticky='nswe')
                
    def on_enter(self, e):
        self.set_active()      
        for slave in self.grid_slaves():
            slave.config(bg=self.active_color)

    def on_leave(self, e):
        self.set_inactive()
        for slave in self.grid_slaves():
            slave.config(bg=self.passive_color)
        
    def clicked_day(self, event):
        self.after(300, self.clicked, event)

    def double_clicked_day(self, event):
        self.double_clicked=True
        
    def clicked(self,event):
        if self.double_clicked:
            self.double_clicked=False
            self.double_clicked_once=True
            print('Doppelklick auf ' + str(self.number) + ' (Todo: Fenster öffnen)')
            self.clicked_day=self.number
                
        else:
            self['background'] = self.active_color
            print(str(self.number) + ' wurde geklickt!')
            #self._eventlist.append(DayClickedEvent(self.number))  

    def set_active(self):
        self.config(bg=self.active_color)

    def set_inactive(self):
        self.config(bg=self.passive_color)

    def change_day(self, new_day): # wird das wo verwendet?? - sonst löschen!
        self._day_text=new_day
        self.day_label['text']=self._day_text

    def change_textcolor(self, new_color):
        self.day_label['foreground']=new_color

    def add_logo(self, logo):
        if not self.mode == 0:
            return False
        nr_of_logos=len(self.active_logos)
        if nr_of_logos<4 and not logo.name in self.active_logos:
            img=logo.image
            self.logolabels[nr_of_logos].configure(image=img)
            self.logolabels[nr_of_logos].image=img
            self.active_logos.append(logo.name)
            return True
        return False

    def add_text(self, text):
        if not self.mode == 0:
            return False
        nr_of_logos=len(self.active_logos) #rename! vlt. nr_of_items
        if nr_of_logos<4 and not 'text' in self.active_logos:
            self.logolabels[nr_of_logos].configure(text=text)
            self.active_logos.append('text')
            return True
        return False
    
    def delete_logo(self, logo):
        if not self.mode == 0:
            return False
        for i,logoitem in enumerate(self.active_logos):
            if logoitem==logo.name:
                img=''
                self.logolabels[i].configure(image=img)
                self.logolabels[i].image=img
                del self.active_logos[i]

    def delete_text(self):
        if not self.mode == 0:
            return False
        for i,logoitem in enumerate(self.active_logos):
            if logoitem=='text':
                self.logolabels[i].configure(text='')
                del self.active_logos[i]
                
    def delete_all_logos(self): #rename .. items
        if not mode == 0:
            return False
        for label in self.logolabels:
            label.configure(text='')
            img=''
            label.configure(image=img)
            label.image=img
        self.active_logos=[]

    @property
    def was_double_clicked(self):
        return self.double_clicked_once
    
    @property
    def number(self):#sollte gelöscht werden, number ist komische bezeichnung!
        return self._day_text

    @property
    def from_actual_month(self):
        return self.day_label['foreground']=='black'
    
    @property
    def is_active(self):
        return self['background']==self.active_color

    @property
    def eventlist(self):
        return self._eventlist

    @property
    def day(self):
        day=1
        try:
            day = int(self._day_text)
        except:
            print('Exception, Tag kann nicht in int gecastet werden: ' + self._day_text)
            day = 1 #mieser ansatz aber temporär okay TODO
        return day

    def event_done(self):
        print('not implemented yet')
        return
示例#21
0
# - - - - - - - - - - - - - - - - - - - - - - - - - - - -

if __name__ == '__main__':
    #Tkinter
    root = Tk()
    root.title("Labelling tool")
    root.bind("<Key>", KeyPress)
    root.protocol("WM_DELETE_WINDOW", Exit)
    picturebox = Label(root,
                       text='',
                       compound='center',
                       font=("Times", 150),
                       fg="white")
    picturebox.grid(rowspan=20, column=0)
    picturebox.bind('<Motion>', Motion)

    v = [split(i)[1] for i in allFileList]
    menu = Combobox(root,
                    values=v,
                    width=18,
                    state="readonly",
                    justify="center")
    menu.grid(row=0, column=1, columnspan=2)
    menu.current(0)
    menu.bind("<<ComboboxSelected>>", change_click)

    label = [
        Button(root,
               text=f'{i+1}',
               fg="gray",
示例#22
0
class StatusBar(Frame, Subscriber):  # pylint: disable=too-many-ancestors
    """
        A status bar that displays the status of the device.
        Date, Time, Internet connectivity, OBD communication
    """
    
    date_label = None
    time_label = None
    wifi_symbol = None
    img_wifi = None
    img_no_wifi = None
    weekdays = None
    def_date = "---, --.--.----"
    def_time = "--:--:--"
    # Private methods
    def __init__(self, *args, **kwargs):
        Frame.__init__(self, *args, **kwargs)
        self.__initialize()
        self.__initialize_widgets()
        self.__place_widgets()

    def __initialize(self):
        self.status_bar_font = font.Font(family="FreeMono", size=14, weight="bold")
        self.img_no_wifi = PhotoImage(file=r"img/white-no-wifi.png")
        self.img_wifi = PhotoImage(file=r"img/white-wifi.png")
        self.weekdays = ["mán", "þri", "mið", "fim", "fös", "lau", "sun"]

    def __initialize_widgets(self):
        self.date_label = Label(self,
                                text=self.def_date,
                                background="black",
                                fg="white",
                                font=self.status_bar_font)

        self.time_label = Label(self,
                                text=self.def_time,
                                background="black",
                                fg="white",
                                font=self.status_bar_font)

        self.wifi_symbol = Label(self,
                                image=self.img_no_wifi,
                                background="black",
                                fg="white")

    def __place_widgets(self):
        self.date_label.pack(side=LEFT, padx=(3, 0))
        self.time_label.pack(side=RIGHT, padx=(0, 3))
        self.wifi_symbol.pack(side=RIGHT, padx=(0, 3))

    # Public methods
    def set_date(self, date):
        """Sets the date in the status bar according to a pre-determined format."""
        weekday = self.weekdays[date.weekday()]
        self.date_label.config(text=date.strftime("{0}, %d.%m.%Y".format(weekday)))

    def set_time(self, date):
        """Sets the time in the status bar according to a pre-determined format."""
        self.time_label.config(text=date.strftime("%H:%M:%S"))

    def update_wifi_symbol(self, hasInternet):
        """Updates the Wi-Fi symbol in the status bar."""
        if hasInternet:
            self.wifi_symbol.config(image=self.img_wifi)
        else:
            self.wifi_symbol.config(image=self.img_no_wifi)

    def update(self, message, pvt):
        if pvt.valid.validDate:
            self.set_date(pvt.getDate())
        else:
            self.date_label.config(text=self.def_date)

        if pvt.valid.validTime:
            self.set_time(pvt.getDate())
        else:
            self.time_label.config(text=self.def_time)
    
    def set_background_color(self, color):
        self.configure(background=color)
        self.date_label.configure(background=color)
        self.time_label.configure(background=color)

    def set_text_color(self, color):
        self.date_label.configure(fg=color)
        self.time_label.configure(fg=color)

    def bind(self, button, callback, add_to_child_views):
        super(StatusBar, self).bind(button, callback)
        if add_to_child_views:
            self.date_label.bind(button, callback)
            self.time_label.bind(button, callback)
            self.wifi_symbol.bind(button, callback)
示例#23
0
label.grid(row=0, column=0, sticky="nsew", padx=1, pady=1)
label = Label(frame4, text="Señal #1")
label.grid(row=1, column=0, sticky="nsew", padx=1, pady=1)
label = Label(frame4, text="Señal #2")
label.grid(row=2, column=0, sticky="nsew", padx=1, pady=1)
label = Label(frame4, text="Señal #3")
label.grid(row=3, column=0, sticky="nsew", padx=1, pady=1)
#Columna #1(Duración)
label = Label(frame4, text="Duraciones")
label.grid(row=0, column=1, sticky="nsew", padx=1, pady=1)
#Columna #2(Ubicación)
label = Label(frame4, text="Ubicación")
label.grid(row=0, column=2, sticky="nsew", padx=1, pady=1)
labelx = Label(frame4, text='Ubicación #1')  #Señal 1
labelx.grid(row=1, column=2, sticky="nsew", padx=1, pady=1)
labelx.bind("<Button>", OpenPath)
labelx = Label(frame4, text='Ubicación #2')  #Señal 2
labelx.grid(row=2, column=2, sticky="nsew", padx=1, pady=1)
labelx.bind("<Button>", OpenPath)
labelx = Label(frame4, text='Ubicación #3')  #Señal 3
labelx.grid(row=3, column=2, sticky="nsew", padx=1, pady=1)
labelx.bind("<Button>", OpenPath)
#Columna #3(Botón de play)
label = Label(frame4, text="Reproducir Señal")
label.grid(row=0, column=3, sticky="nsew", padx=1, pady=1)
btn2 = tk.Button(frame4, text="Play Signal #1")
btn2.grid(row=1, column=3, sticky="nsew", padx=1, pady=1)
btn3 = tk.Button(frame4, text="Play Signal #2")
btn3.grid(row=2, column=3, sticky="nsew", padx=1, pady=1)
btn4 = tk.Button(frame4, text="Play Signal #3")
btn4.grid(row=3, column=3, sticky="nsew", padx=1, pady=1)
示例#24
0
class DrowingApp:
    def __init__(self, master, WIDTH=1100, HEIGHT=600):
        master.title("GUI HW1 By Shani & Idan")
        self.init_Val()
        self.create_canvas(master, WIDTH, HEIGHT)
        master.attributes("-transparentcolor", "red")
        self.create_upper_menu()
        # lower section
        self.lower_frame = Canvas(self.master, bg='#c9daf8', bd=5)
        self.lower_frame.place(relx=0.5,
                               rely=0.25,
                               relwidth=0.75,
                               relheight=0.6,
                               anchor='n')
        self.lower_frame.bind("<ButtonPress-1>", self.click)

    def create_upper_menu(self):
        # Uper section
        frame = Frame(self.master, bg='#a0dbd1', bd=4)
        frame.place(relx=0.5,
                    rely=0.1,
                    relwidth=0.75,
                    relheight=0.1,
                    anchor='n')
        # Set curve and figure variable and trace changes
        self.figure_val = StringVar(frame)
        self.create_OptionMenu(self.figure_val, frame, option_figure[0], 0.05,
                               option_figure)
        self.curve_val = IntVar(frame)
        self.create_OptionMenu(self.curve_val, frame, option_curve[0], 0.30,
                               option_curve)
        # Set color button
        color = TkinterCustomButton(master=frame,
                                    height=52,
                                    text="Color",
                                    command=self.color_option)
        color.place(relx=0.55)
        # Set clear button
        clear = TkinterCustomButton(
            master=frame,
            height=52,
            text="Clear",
            command=lambda: self.lower_frame.delete("all"))
        clear.place(relx=0.80)

    def create_OptionMenu(self, s, frame, val, loc, func):
        # Set figures variable and trace changes
        s.set(val)
        s.trace("w", self.change_option)
        om = OptionMenu(frame, s, *func)
        om.place(relx=loc, relwidth=0.15, relheight=1)
        om.config(bg="#2874A6")
        om["menu"]["bg"] = "#2874A6"
        om["activebackground"] = "#5499C7"

    def init_Val(self):
        self.my_color = "Black"
        self.my_figure = "Line"
        self.my_curve = 10
        self.my_point = 1
        # Holds the selected point
        self.x = [0, 0, 0, 0]
        self.y = [0, 0, 0, 0]

    def create_canvas(self, master, WIDTH, HEIGHT):
        self.master = master
        self.rootgeometry(WIDTH, HEIGHT)
        self.canvas = Canvas(self.master)
        self.canvas.pack()
        self.background_image = Image.open('bg.PNG')
        self.image_copy = self.background_image.copy()
        self.background = ImageTk.PhotoImage(self.background_image)
        self.loadbackground()

    def change_option(self, *args):
        # Set my_point to first click
        self.my_point == 1
        # Set values
        self.my_figure = self.figure_val.get()
        self.my_curve = self.curve_val.get()

    def click(self, event):
        # Get (x,y)
        if self.my_point == 1:
            # Get first x,y
            self.x[0] = event.x
            self.y[0] = event.y
            self.my_point = 2
            return
        if self.my_point == 2:
            # Get sec x,y
            self.x[1] = event.x
            self.y[1] = event.y
            self.my_point = 3

            # check if line or circle
            # if its cerve get 2 more (x,y)
            if self.my_figure == 'Line':
                self.myLine(self.x[0], self.y[0], self.x[1], self.y[1])
                self.my_point = 1
                return
            elif self.my_figure == 'Circle':
                r = self.getR(self.x[0], self.y[0], self.x[1], self.y[1])
                self.myCircle(self.x[0], self.y[0], r)
                self.my_point = 1
                return
            elif self.my_figure == 'Cerve':
                return

        if self.my_point == 3:
            # Get third x,y
            self.x[2] = event.x
            self.y[2] = event.y
            self.my_point = 4
            return

        if self.my_point == 4:
            # Get fourth x,y
            self.x[3] = event.x
            self.y[3] = event.y
            self.my_point = 1

            self.myCurve(self.x[0], self.y[0], self.x[1], self.y[1], self.x[2],
                         self.y[2], self.x[3], self.y[3])
            return

    def color_option(self):
        # variable to store hexadecimal code of color
        color = colorchooser.askcolor()[1]
        if color != None:
            self.my_color = color
            print(self.my_color)

    def putPixel(self, x_, y_):
        self.lower_frame.create_line(x_,
                                     y_,
                                     x_ + 1,
                                     y_ + 1,
                                     fill=self.my_color)

    # Bersenheim
    def myLine(self, x1, y1, x2, y2):
        dx = x2 - x1
        dy = y2 - y1
        # Determine how steep the line is
        is_steep = abs(dy) > abs(dx)

        # Rotate line
        if is_steep:
            x1, y1 = y1, x1
            x2, y2 = y2, x2

        # Swap start and end points if necessary
        swapped = False
        if x1 > x2:
            x1, x2 = x2, x1
            y1, y2 = y2, y1
            swapped = True

        # Recalculate differentials
        dx = x2 - x1
        dy = y2 - y1

        # Calculate error
        error = int(dx / 2.0)
        ystep = 1 if y1 < y2 else -1

        # Iterate over bounding box generating points between start and end
        y_ = y1
        points = []
        for x_ in range(x1, x2 + 1):
            coord = (y_, x_) if is_steep else (x_, y_)
            points.append(coord)
            error -= abs(dy)
            if error < 0:
                y_ += ystep
                error += dx
        if swapped:
            points.reverse()
        for point in points:
            self.putPixel(point[0], point[1])

    def circle_lines(self, xc, yc, x_, y_):
        self.putPixel(xc + x_, yc + y_)
        self.putPixel(xc - x_, yc + y_)
        self.putPixel(xc + x_, yc - y_)
        self.putPixel(xc - x_, yc - y_)
        self.putPixel(xc + y_, yc + x_)
        self.putPixel(xc - y_, yc + x_)
        self.putPixel(xc + y_, yc - x_)
        self.putPixel(xc - y_, yc - x_)
        return

    def myCircle(self, xc, yc, r):
        x_, y_ = 0, r
        d = 3 - 2 * r
        self.circle_lines(xc, yc, x_, y_)
        while y_ >= x_:
            x_ += 1

            #  check for decision parameter
            #  update d, x, y
            if d > 0:
                y_ -= 1
                d = d + 4 * (x_ - y_) + 10

            else:
                d = d + 4 * x_ + 6
            self.circle_lines(xc, yc, x_, y_)
        return

    def getR(self, x1, y1, x2, y2):
        r = (x2 - x1)**2 + (y2 - y1)**2
        r = (r**0.5)
        return round(r)

    def getVal(self, x1, x2, x3, x4, t):
        ax = -x1 + 3 * x2 - 3 * x3 + x4
        bx = 3 * x1 - 6 * x2 + 3 * x3
        cx = -3 * x1 + 3 * x2
        dx = x1
        res = ax * t**3 + bx * t**2 + cx * t + dx
        return round(res)

    def myCurve(self, x1, x2, x3, x4, y1, y2, y3, y4):
        xt1 = x1
        yt1 = y1

        for t in range(0, self.my_curve + 1):
            pointx = self.getVal(x1, x2, x3, x4, t / self.my_curve)
            pointy = self.getVal(y1, y2, y3, y4, t / self.my_curve)
            self.myLine(xt1, yt1, pointx, pointy)
            xt1 = pointx
            yt1 = pointy
        return

    def loadbackground(self):
        self.label = Label(self.canvas, image=self.background)
        self.label.bind('<Configure>', self.resizeimage)
        self.label.pack(fill='both', expand='yes')

    def rootgeometry(self, WIDTH, HEIGHT):

        self.master.geometry(str(WIDTH) + 'x' + str(HEIGHT))

    def resizeimage(self, event):
        image = self.image_copy.resize(
            (self.master.winfo_width(), self.master.winfo_height()))
        self.image1 = ImageTk.PhotoImage(image)
        self.label.config(image=self.image1)
示例#25
0
        if anchor["Status"] >= Status.Line2Start:
            cv.line(img, anchor["Line2Start"], anchor["Line2End"], (0, 255, 0),
                    1)

    cv2image = cv.cvtColor(img, cv.COLOR_BGR2RGBA)  # 转换颜色从BGR到RGBA
    current_image = Image.fromarray(cv2image)
    imgtk = ImageTk.PhotoImage(image=current_image)
    panel.imgtk = imgtk
    panel.config(image=imgtk)
    root.after(20, render)


root = tk.Tk()
root.title("opencv + tkinter")
root.bind("<Key>", key)

panel = Label(root)  # initialize image panel
panel.bind("<Button-1>", on_click)
panel.bind("<B1-Motion>", on_move)
panel.bind("<ButtonRelease-1>", on_release)
panel.pack(padx=10, pady=10)

nox_hwnd = win32_tools.get_window_hwnd("碧蓝航线")
base_img = image_tools.get_window_shot(nox_hwnd)
img = base_img.copy()

render()

root.mainloop()
cv.destroyAllWindows()
示例#26
0
class GUI:
    def __init__(self, master):
        """initialize GUI"""
        self.root = master
        self.on = True
        Tk().withdraw()

        self.starttime = datetime.now()

        # status bar, info for user
        self.statusString = StringVar()
        self.statusText = 'Ready'
        self.statusString.set(self.statusText)
        self.comparatorStatus = 'inactive'
        # self.comparatorStatuses = ['inactive', 'active',
        #                            'steady', 'moving', 'paused', 'finished']
                                   # 2 manual statuses + 4 auto statuses

        self.levelStatus = StringVar()
        self.ifmStatus = StringVar()
        self.nivelStatus = StringVar()
        self.thermoStatus = StringVar()

        self.active = 0  # 0 - inactive state, 1 - active (in motion), 2 - steady (waiting while taking data)
        self.auto = 0

        # COMPARATOR MOTION CONTROL
        self.step = StringVar()  # mm
        self.begin = StringVar()  # mm
        self.end = StringVar()  # mm

        self.autoVal = IntVar()

        self.labelTop = StringVar()
        self.labelTop.set('VERTICAL COMPARATOR')

        # LABELS ON BUTTONS
        self.label10 = StringVar()  # initialize
        self.label11 = StringVar()  # start/stop
        self.label12 = StringVar()  # pause/continue
        self.label21 = StringVar()  # manual
        self.label22 = StringVar()  # auto
        self.label31 = StringVar()  # step
        self.label32 = StringVar()  # start
        self.label33 = StringVar()  # stop
        self.label51 = StringVar()  # manual read interferometer
        self.label52 = StringVar()  # manual read digi level
        self.label53 = StringVar()  # manual read nivel (inclinometer)
        self.label54 = StringVar()  # manual read thermometer

        self.autoVal.set(0)

        # init PLC, interferometer and level
        self.plc = Comparator(comsettings['COMPARATOR_PORT'], int(comsettings['COMPARATOR_BAUD']))
        self.conn = self.plc.conn
        self.paused = None
        self.ifm = Interferometer(comsettings['IFM_PORT'], int(comsettings['IFM_BAUD']))
        self.level = Level(comsettings['LEVEL_PORT'], int(comsettings['LEVEL_BAUD']))
        self.nivel = Nivel(comsettings['NIVEL_PORT'], int(comsettings['NIVEL_BAUD']))
        self.thermo = Thermometer(comsettings['THERMO_PORT'], int(comsettings['THERMO_BAUD']))

        self.observer = ''  # operator

        self.label10.set('Initialize')
        self.label11.set({0: 'START', 1: 'STOP', 2:'STOP'}[self.active])  # start/stop
        self.setStatus({0: 'ready', 1: 'active', 2:'steady'}[self.active])

        self.label12.set('PAUSE')

        self.label21.set('MANUAL')  # manual
        self.label22.set('AUTO')  # auto

        self.label31.set('LOW')  # start height
        self.label32.set('HIGH')  # stop height
        self.label33.set('STEP')  # step

        self.label51.set('READ IFM')  # read interferometer
        self.label52.set('READ LVL')  # read digi level
        self.label53.set('READ NVL')  # read inclinometer
        self.label54.set('READ THM')  # read thermometer

        self.chksumText = StringVar()
        self.responseText = StringVar()

        self.timestring = StringVar()
        self.connstring = StringVar()

        # self.queue = queue.Queue()
        self.timerthread = threading.Thread(target=self.timer, name='Timer')
        self.timerthread.start()

        self.readdata = ''
        self.connthread = threading.Thread(target=self.checkConnection, name='ConnChk')
        self.connthread.start()

        self.statusthread = threading.Thread(target=self.checkStatus, name='StatChk')
        self.statusthread.start()

        self.readexternalsthread = threading.Thread(target=self.readExternals, name='ReadExt')
        self.readexternalsthread.start()

        self.autologthread = threading.Thread(target=self.autolog, name='Autolog')
        self.autologthread.start()

        # starttimer()
        # startautolog()
        # startautoserialcheck()

    # def toggleStartStop(self):
    #    # if start then stop else otherwise
    #    # change button and text color if possible
    #    pass

    def timer(self):
        while self.on:
            dt = datetime.now() - self.starttime
            self.timestring.set('%-10s' % str(dt).split('.')[0])
            time.sleep(0.1)

    def autolog(self, timeout=60):
        while self.on:
            print('Autolog')
            (s, low, hi, step, ifm, lvl, nvl, thm, obs) = tuple(['']*9)
            try:
                s = self.statusText
            except BaseException:
                s = 'N/A'
            try:
                low = self.lowEntry.get().strip()
            except BaseException:
                low = 'N/A'
            try:
                hi = self.hiEntry.get().strip()
            except BaseException:
                hi = 'N/A'
            try:
                step = self.stepEntry.get().strip()
            except BaseException:
                step = 'N/A'
            try:
                ifm = self.ifm.getReading()
            except BaseException:
                ifm = 'N/A'
            try:
                lvl = self.level.getReading()
            except BaseException:
                lvl = 'N/A'
            try:
                nvl = self.nivel.getReading()
            except BaseException:
                nvl = 'N/A'
            try:
                thm = self.thermo.getReading()
            except BaseException:
                thm = 'N/A'
            try:
                obs = self.entryObserver.get().strip()
            except BaseException:
                obs = 'N/A'
            log('AUTOLOG! status: %s, low: %s, hi: %s, step: %s, ifm: %s, lvl: %s, nvl:%s, thm: %s, obs: %s' % (
            s, low, hi, step, ifm, lvl, nvl, thm, obs))
            time.sleep(timeout)

    def checkConnection(self):
        connection = False
        while self.on:
            if self.conn:
                try:
                    d = self.conn.read(1)
                    self.readdata += d
                    connection = True
                except:
                    self.conn.close()
                    try:
                        self.connect()
                    except:
                        connection = False
            else:
                try:
                    self.connect()
                except:
                    connection = False
            self.connstring.set({True: 'isConn', False: 'notConn'}[connection])
            time.sleep(0.5)

    def checkStatus(self):
        if self.conn:
            moving = self.plc.query('is_moving')
            if moving is None:
                self.status = 'unknown'
            elif not self.auto:
                if moving:
                    self.status = 'active'
                else:
                    self.status = 'inactive'
            else:
                if moving:
                    self.status = 'moving'
                else:
                    if self.paused:
                        self.status = 'paused'
                    else:
                        self.status = 'steady'
        else:
            self.status = 'not connected'

    def readExternals(self):
        while self.on:
            # self.getIfm()
            # self.getLevel()
            self.getNivel()
            self.getThermo()
            time.sleep(15)

    def evaluateEntries(self):
        s, b, e = self.stepEntry, self.beginEntry, self.endEntry
        res = [None, None, None]
        for i in range(3):
            try:
                res[i] = float([s, b, e][i])
            except:
                pass  # leave it None
        if b > e and s > 0:  # if step is negative, it can move downwards (from hi to low)
            b, e = e, b  # otherwise it begin and end must be changed if b>e
        elif b < e and s < 0:
            b, e = e, b

        # INPUT IN MM !! cannot recognize 0.5mm from 0.5m  step or 3mm vs 3m end
        # input values converted to mm
        # [s,b,e] = [i*1000. if (i is not None and i<5.) else i for i in [s,b,e]]
        return s, b, e

    def emptyRow(self, nrow):
        Label(self.fr, text="", bg=bgcolor).grid(row=nrow, column=0)

    def setStatus(self, text):
        self.statusText = text
        self.statusString.set(self.statusText)

    def setIfmStatus(self, text):
        self.ifmStatus.set(text)

    def setLevelStatus(self, text):
        self.levelStatus.set(text)

    def setNivelStatus(self, text):
        self.nivelStatus.set(text)

    def setThermoStatus(self, text):
        self.thermoStatus.set(text)

    def getIfm(self):
        # log('Get Ifm reading')
        response = self.ifm.getReading() or "No response"
        self.setIfmStatus(response)
        return response

    def getLevel(self):
        # log('Get Level reading')
        response = self.level.getReading() or "No response"
        self.setLevelStatus(response)
        return response

    def getNivel(self):
        # log('Get Nivel reading')
        response = '-'.join(map(str,self.nivel.getReading())) if any(self.nivel.getReading()) else "No response"
        self.setNivelStatus(response)
        return response

    def getThermo(self):
        # log('Get Thermo reading')
        response = self.thermo.getReading() or "No response"
        self.setThermoStatus(response)
        return response

    #    #set stop button
    #    def setStop(self):
    #        pass
    #
    #    #set start
    #    def setStart(self):
    #        pass

    # toggle start stop
    def startStop(self):
        # ask comparator if moving, then set "not response"
        self.active = not self.active
        # self.setStatus({0: 'ready', 1: 'active'}[self.active])
        self.setStatus(self.comparatorStatus)

        self.label10.set({0: 'START', 1: 'STOP'}[self.active])
        self.buttonStartStop.configure(bg=startstopbg[self.active],
                                       fg=startstopfg[self.active])
        print(self.active)

        self.observer = self.entryObserver.get().strip()

        if not self.active:
            log('CMP stopped %s' % self.observer)
        else:
            log('CMP started %s' % self.observer)

        if self.active:
            pass  # action after comparator is stopped
        else:
            pass  # action after comparator is started

    # CURRENT_POSITION, NEXT_POSITION, TARGET_POSITION, ITERATION
    def writePauseParams(self,**params):
        with open('.pause') as f:
            f.write('\n'.join([k+' '+' '.join(vals) for k, vals in params.items()]))
        return True

    def readPauseParams(self):
        params = {}
        with open('.pause','r') as f:
            for line in f.readlines():
                key = line.split()[0]
                vals = line.split()[1:]
                params[key] = vals
        os.remove('.pause')
        return params

    def pauseSession(self):
        self.paused = True
        self.stop()
        self.writePauseParams()

    def continueSession(self):
        self.paused = False
        params = self.readPauseParams()
        self.moveto(params['NEXT_POS'])
        self.session(float(params['NEXT_POS']), float(params['TARGET_POS']),
                          float(params['STEP']), int(params['NEXT_ITER']))

    def session(self, **params):
        start = float(params.get('START_POS'))
        target = float(params.get('TARGET_POS'))
        step = float(params.get('STEP',5))
        iteration = int(params.get('NEXT_ITER',0))
        self.plc.moveto(start)
        self.paused = False
        op = operator.le if step > 0 else operator.ge
        while op(self.plc.getPosition(), target):
            iteration += 1
            self.getMeasurement()
            next_position = self.plc.getPosition() + step
            if next_position < target:
                self.plc.moveto(next_position)


    def initialize(self):
        if not self.plc.isInit():
            log('Initialize')
        else:
            log('Already initialized, reinitialize.')
        self.plc.initialize()

    def pause(self):
        # comparator status:
        # man/inactive, man/active,
        # auto/steady (measurement), auto/active, auto/paused, auto/finished
        #['inactive', 'active', 'steady', 'moving', 'paused', 'finished']
        if self.comparatorStatus in ('moving', 'steady'):
            self.pauseSession()

        elif self.comparatorStatus == 'paused':
            self.continueSession()

        # active / inactive - button should be disabled


    def stop(self):
        self.plc.command('STOP')

    def getEntries(self):
        return self.stepEntry, self.beginEntry, self.endEntry

    def close(self):
        self.on = False
        # for thread in (self.timerthread, self.connthread, self.statusthread, self.autologthread, self.readexternalsthread):
        #     thread.join()
        # TODO CLOSE ALL CONNECTIONS!!
        if self.active:
            self.startStop()
        self.root.destroy()
        self.root.quit()

    def gotoLow(self):
        low = None
        self.setStatus('Going to LOW')
        try:
            low = float(self.lowEntry.get().strip())
        except:
            pass
        pass  # move carriage to set low
        return low

    def gotoHi(self):
        hi = None
        self.setStatus('Going to HIGH')
        try:
            hi = float(self.hiEntry.get().strip())
        except:
            pass
        pass  # move carriage to set low
        return hi

    def moveStep(self):
        pos = self.plc.getPosition() or 0  # remove 0 when connection established
        step = 0
        try:
            step = float(self.stepEntry.get().strip())
        except BaseException:
            log('Cannot determine step entry.')
        targetpos = pos + step
        if step != 0:
            self.setStatus('Moving to %f' % targetpos)
            self.plc.moveto(targetpos)
        return targetpos

    def resetIfmStatus(self):
        self.ifmStatus.set('')

    def resetLevelStatus(self):
        self.levelStatus.set('')

    def resetNivelStatus(self):
        self.nivelStatus.set('')

    def resetThermoStatus(self):
        self.thermoStatus.set('')

    def submit(self):
        calculate_checksum = True

        port = self.portEntry.get().strip()
        message = self.messageEntry.get()
        chksumtyp = self.portChecksumType.get()

        from externals import RS232
        from pycrc import pycrc, crc_algorithms, Crc

        rs = RS232()
        r = rs.connect(port, baud=38400)
        if r:
            print ('Successfully connected to %s' % r.name)


        checksum = ''
        if calculate_checksum:
            from pycrc.crc_algorithm import Crc

            # params = filter(lambda x: x['name']==chksumtyp, cmodels)[0]
            params = {'width': 16, 'poly':0x1021, 'reflect_in':True,
                      'xor_in':0x0000, 'reflect_out':True, 'xor_out':0x0000}

            crc = Crc(**params)
            print("{0:#x}".format(crc.bit_by_bit(message)))
            # crc = Crc(width=16, poly=0x8005,
            #             reflect_in = True, xor_in = 0x0000,
            #             reflect_out = True, xor_out = 0x0000)
            # >> > print("{0:#x}".format(crc.bit_by_bit("123456789")))
            # >> > print("{0:#x}".format(crc.bit_by_bit_fast("123456789")))
            # >> > print("{0:#x}".format(crc.table_driven("123456789")))



        rs.send()


        # self.chksumLabel = (self.fr, textvariable = self.chksumText, anchor = 'w',
        #                                                                       bg = bgcolor, fg = statuscolor, font = (
        # "Calibri", 9))
        # self.chksumLabel.grid(row=23, column=2)
        #
        # buttonSubmit = Button(self.fr, text="SUBMIT", width=15, justify='center',
        #                       bg="black", fg="yellow", command=self.submit,
        #                       font=("Calibri", 14, "bold"))
        # buttonSubmit.grid(row=23, column=0)
        #
        # self.responseLabel = (self.fr, textvariable = self.responseText, anchor = 'w',
        #                                                                           bg = bgcolor, fg = statuscolor, font = (
        # "Calibri", 9))
        # self.responseLabel.grid(row=23, column=1)
        #
        # self.emptyRow(24)



    def mainDialog(self):

        self.basicframe = Frame(self.root)
        self.basicframe.grid()
        self.basicframe.configure(bg=bgcolor)

        self.fr = Frame(self.basicframe)
        self.fr.grid(row=0, column=0, sticky='new')  # , sticky='W')
        self.fr.configure(bg=bgcolor)

        # Grid.rowconfigure(root, 0, weight=1)
        Grid.columnconfigure(root, 0, weight=1)

        self.emptyRow(0)

        Label(self.fr, textvariable=self.labelTop,
              justify='center', bg=bgcolor, font=("Calibri", 24)
              ).grid(row=1, column=0, columnspan=3, sticky='we')

        self.emptyRow(2)

        Label(self.fr, text='STATUS:', justify='left', anchor='w',
              bg=bgcolor, fg=statuscolor, font=("Calibri", 12)
              ).grid(row=3, column=0, sticky='we', padx=(5, 0))

        self.statusLine = Label(self.fr, textvariable=self.statusString,
                                justify='left', anchor='w', bg=bgcolor, fg=statuscolor,
                                font=("Calibri", 14, "bold")
                                ).grid(row=3, column=1, columnspan=2, sticky='we')

        self.emptyRow(4)

        # AUTO / MANUAL  self.my_var.set(1)
        self.buttonManual = Radiobutton(self.fr, text="MANUAL",
                                     variable=self.auto,
                                     value=0,
                                     width=15,
                                     justify='center',
                                     # bg=buttoncolor2,
                                     bg="moccasin",
                                     indicatoron=0)  # self.exit_root)
        self.buttonManual.grid(row=5, column=0, sticky='ew', padx=(0, 10))
        # self.buttonManual.configure(state='selected')

        self.buttonAuto = Radiobutton(self.fr, text="AUTO",
                                   variable=self.auto,
                                   value=1,
                                   width=15, justify='center',
                                   # bg=buttoncolor2,
                                   bg="moccasin",
                                   indicatoron=0)  # self.exit_root)
        self.buttonAuto.grid(row=5, column=2, sticky='ew', padx=(10, 0))

        self.emptyRow(6)

        #should be disabled if initialized already
        self.buttonInitialize = Button(self.fr, text='Initialize',
                                   justify='center', bg=buttoncolor, command=self.initialize)
        self.buttonInitialize.grid(row=7, column=0, sticky='nsew')

        self.buttonStartStop = Button(self.fr, textvariable=self.label11,
                                   command=self.startStop,
                                   bg=startstopbg[self.active],
                                   fg=startstopfg[self.active],
                                   font=("Calibri", 16, "bold"),
                                   width=10)
        self.buttonStartStop.grid(row=7, column=1, sticky='nsew')

        self.buttonPause = Button(self.fr, textvariable=self.label12,
                                   justify='center', bg=buttoncolor,
                                   state={0: 'disabled', 1: 'enabled'}[self.auto],
                                   command=self.pause)
        self.buttonPause.grid(row=7, column=2, sticky='nsew')

        self.emptyRow(8)

        # put Labels here

        Label(self.fr, textvariable=self.label31, justify='center',
              bg=bgcolor, fg=statuscolor, font=("Calibri", 10)
              ).grid(row=8, column=0, sticky='we')
        Label(self.fr, textvariable=self.label32, justify='center',
              bg=bgcolor, fg=statuscolor, font=("Calibri", 10)
              ).grid(row=8, column=1, sticky='we')
        Label(self.fr, textvariable=self.label33, justify='center',
              bg=bgcolor, fg=statuscolor, font=("Calibri", 10)
              ).grid(row=8, column=2, sticky='we')

        # input boxes: step start stop (mm)
        self.lowEntry = Entry(self.fr, width=20, bd=3, justify='right',
                              bg=inputbox, fg=statuscolor)
        self.lowEntry.grid(row=9, column=0, sticky='we')  # , columnspan=2)
        # SET DEFAULT LOW
        # self.lowEntry.delete(0,END)
        # self.lowEntry.insert(0, MINPOS)

        self.hiEntry = Entry(self.fr, width=20, bd=3, justify='right',
                             bg=inputbox, fg=statuscolor)
        self.hiEntry.grid(row=9, column=1, sticky='we')  # , columnspan=2)
        # SET DEFAULT HIGH
        # self.hiEntry.delete(0,END)
        # self.hiEntry.insert(0, MAXPOS)

        self.stepEntry = Entry(self.fr, width=20, bd=3, justify='right',
                               bg=inputbox, fg=statuscolor)
        self.stepEntry.grid(row=9, column=2, sticky='we')  # , columnspan=2)

        # put buttons for  GOTO and MOVE
        self.butGotoLow = Button(self.fr, text="Go To Low",
                                 justify='center', bg=buttoncolor, command=self.gotoLow)
        self.butGotoLow.grid(row=10, column=0, sticky='we')

        self.butGotoHi = Button(self.fr, text="Go To High",
                                justify='center', bg=buttoncolor, command=self.gotoHi)
        self.butGotoHi.grid(row=10, column=1, sticky='we')

        self.butMoveStep = Button(self.fr, text="Move a Step",
                                  justify='center', bg=buttoncolor, command=self.moveStep)
        self.butMoveStep.grid(row=10, column=2, sticky='we')

        self.emptyRow(11)

        Label(self.fr, text='EXTERNAL SENSORS', justify='left',
              anchor='w', bg=bgcolor, fg=statuscolor, font=("Calibri", 12)
              ).grid(row=12, column=0, columnspan=3, sticky='we', padx=(5, 0))

        # function buttons


        # RIadok 13-16: Externals
        # Interferometer
        buttonIfm = Button(self.fr, text="Read IFM", width=15, justify='center',
                        bg=buttoncolor, command=self.getIfm)  # self.exit_root)
        buttonIfm.grid(row=13, column=0, sticky='we')

        self.labelIfmStatus = Label(self.fr, textvariable=self.ifmStatus,
                                  justify='left', anchor='w', bg=bgcolor, fg=statuscolor,
                                  font=("Calibri", 12))
        self.labelIfmStatus.grid(row=13, column=1, columnspan=2,
                               sticky='we', padx=(15, 0))
        self.labelIfmStatus.bind('<Button-1>', self.resetIfmStatus)

        # Digital level (Leica /Trimble)
        buttonLevel = Button(self.fr, text="Read Level", width=15, justify='center',
                        bg=buttoncolor, command=self.getLevel)  # self.exit_root)
        buttonLevel.grid(row=14, column=0, sticky='we')

        self.labelLevelStatus = Label(self.fr, textvariable=self.levelStatus,
                                  justify='left', anchor='w', bg=bgcolor, fg=statuscolor,
                                  font=("Calibri", 12))
        self.labelLevelStatus.grid(row=14, column=1, columnspan=2,
                               sticky='we', padx=(15, 0))
        self.labelLevelStatus.bind('<Button-1>', self.resetLevelStatus)

        # Nivel - inclinometer
        buttonNivel = Button(self.fr, text="Read Nivel", width=15, justify='center',
                        bg=buttoncolor, command=self.getNivel)  # self.exit_root)
        buttonNivel.grid(row=15, column=0, sticky='we')

        self.labelNivelStatus = Label(self.fr, textvariable=self.nivelStatus,
                                  justify='left', anchor='w', bg=bgcolor, fg=statuscolor,
                                  font=("Calibri", 12))
        self.labelNivelStatus.grid(row=15, column=1, columnspan=2,
                               sticky='we', padx=(15, 0))
        self.labelNivelStatus.bind('<Button-1>', self.resetNivelStatus)

        # Thermometer line
        buttonThermo = Button(self.fr, text="Read Thermo", width=15, justify='center',
                        bg=buttoncolor, command=self.getThermo)  # self.exit_root)
        buttonThermo.grid(row=16, column=0, sticky='we')

        self.labelThermoStatus = Label(self.fr, textvariable=self.thermoStatus,
                                  justify='left', anchor='w', bg=bgcolor, fg=statuscolor,
                                  font=("Calibri", 12))
        self.labelThermoStatus.grid(row=16, column=1, columnspan=2,
                               sticky='we', padx=(15, 0))
        self.labelThermoStatus.bind('<Button-1>', self.resetThermoStatus)

        self.emptyRow(17)

        Label(self.fr, text='OBSERVER:', anchor='w', justify='left',
              bg=bgcolor, fg=statuscolor, font=("Calibri", 12)
              ).grid(row=19, column=0, sticky='we', padx=(5, 0))
        self.entryObserver = Entry(self.fr, textvariable=self.observer,
                                   bg=inputbox, fg=statuscolor, font=("Calibri", 12),
                                   justify='left')
        self.entryObserver.grid(row=19, column=1, columnspan=2, sticky='we')

        # row 18> empty (or test connection)
        self.emptyRow(20)

        if ADMIN_MODE:
            # port, message, checksum_type?, resulting checksum?, submit, response
            self.portEntry = Entry(self.fr, width=20, bd=3, justify='left',
                                   bg=inputbox, fg=statuscolor)
            self.portEntry.grid(row=21, column=0, sticky='we')
            Label(self.fr, text='PORT', anchor='w', justify='left',
                  bg=bgcolor, fg=statuscolor, font=("Calibri", 12)
                  ).grid(row=22, column=0, sticky='we', padx=(5, 0))

            self.messageEntry = Entry(self.fr, width=20, bd=3, justify='left',
                                   bg=inputbox, fg=statuscolor)
            self.messageEntry.grid(row=21, column=1, sticky='we')
            Label(self.fr, text='MESSAGE', anchor='w', justify='left',
                  bg=bgcolor, fg=statuscolor, font=("Calibri", 12)
                  ).grid(row=22, column=1, sticky='we', padx=(5, 0))

            self.portChecksumType = Entry(self.fr, width=20, bd=3, justify='left',
                                   bg=inputbox, fg=statuscolor)
            self.portChecksumType.grid(row=21, column=2, sticky = 'we')
            Label(self.fr, text='CHKSUM TYPE', anchor='w', justify='left',
                        bg=bgcolor, fg=statuscolor, font=("Calibri", 12)
                        ).grid(row=22, column=2, sticky='we', padx=(5, 0))


            self.chksumLabel = Label(self.fr, textvariable=self.chksumText, anchor='w',
                                bg=bgcolor, fg=statuscolor, font=("Calibri", 9))
            self.chksumLabel.grid(row=23, column=2)

            buttonSubmit = Button(self.fr, text="SUBMIT", width=15, justify='center',
                             bg="black", fg="yellow", command=self.submit,
                             font=("Calibri", 14, "bold"))
            buttonSubmit.grid(row=23, column=0)


            self.responseLabel = Label(self.fr, textvariable=self.responseText, anchor='w',
                                bg=bgcolor, fg=statuscolor, font=("Calibri", 9))
            self.responseLabel.grid(row=23, column=1)

            self.emptyRow(24)


        lastLine = 21 if not ADMIN_MODE else 25

        self.timeLabel = Label(self.fr, textvariable=self.timestring,
                               anchor='w', bg=bgcolor, fg=statuscolor,
                               font=("Calibri", 9))
        self.timeLabel.grid(row=lastLine, column=0)

        self.connLabel = Label(self.fr, textvariable=self.connstring,
                               anchor='w', bg=bgcolor, fg=statuscolor,
                               font=("Calibri", 9))
        self.connLabel.grid(row=lastLine, column=1)

        butexit = Button(self.fr, text="EXIT", width=15, justify='center',
                         bg="black", fg="yellow", command=self.close,
                         font=("Calibri", 14, "bold"))
        butexit.grid(row=lastLine, column=2)
示例#27
0
from tkinter import Tk, Label
root = Tk()

label = Label(root, text='I am a label. Click me.')
label.pack()


def my_callback():
    print('Label was clicked.')


label.bind("<Button-1>", lambda e: my_callback())

root.mainloop()
示例#28
0
class Time(Frame):
    """
	A tkinter widget for setting and getting a time. The 
	get_time method will return a datetime.time object
	based off of the input in the entries.
	"""
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        width = 3
        self.hours = Entry(self, width=width)
        self.hours.insert(0, "10")
        self.hours.bind("<FocusOut>", self.__verify_hours)
        self.hours.grid(row=0, column=0)
        Label(self, text=":").grid(row=0, column=1)

        self.minutes = Entry(self, width=width)
        self.minutes.insert(0, "00")
        self.minutes.bind("<FocusOut>", self.__verify_minutes)
        self.minutes.grid(row=0, column=2)

        self.am_pm = Label(self, text='AM', cursor='hand2')
        self.am_pm.bind(
            "<Button-1>", lambda e: e.widget.config(text='AM' if e.widget.cget(
                'text') == 'PM' else 'PM'))
        self.am_pm.grid(row=0, column=3)

    def __set_entry(self, entry, value):
        entry.delete(0, END)
        entry.insert(0, value)

    def __verify_hours(self, event):
        try:
            num = int(event.widget.get())
            if num < 1 or num > 12:
                raise Exception()

            self.__set_entry(event.widget, str(num))
        except:
            self.__set_entry(event.widget, '')

    def __verify_minutes(self, event):
        try:
            num = int(event.widget.get())
            if num < 0 or num > 59:
                raise Exception()

            if num < 10:
                self.__set_entry(event.widget, "0{}".format(num))
            else:
                self.__set_entry(event.widget, str(num))
        except:
            self.__set_entry(event.widget, '')

    def get_time(self):
        if not all((self.hours.get(), self.minutes.get())):
            raise Exception("ERROR. Enter a time.")

        # No need to verify our hours and minutes are ints;
        # we already did that checking on input
        hours = int(self.hours.get())

        if self.am_pm.cget('text') == 'PM' and hours != 12:
            hours += 12
        elif self.am_pm.cget('text') == 'AM' and hours == 12:
            hours -= 12

        return datetime.time(hours, int(self.minutes.get()))
示例#29
0
    def __init__(self, *args, **kwargs):
        Frame.__init__(self, *args, **kwargs);
        
        self.toForeGround
        ################### init, main config ######################
        container = Frame(self, bg=bgColor);
        container.pack(side="top", fill="both", expand=True);       
        
        
        self.ft1 = font.Font(family='Arial', size=11);     
        self.ft2 = font.Font(family='MS Gothic', size=10);
        self.ft3 = font.Font(family='Arial', size=9);
        self.ft4 = font.Font(family='Arial', size=10);
        self.ft5 = font.Font(family='Arial', size=14);
        self.ft6 = font.Font(family="Courier", size = 9);
        
        self.p1 = Page1(container, bg=container["background"]);
        self.p2 = Page2(container, bg=container["background"]);
        self.p3 = Page3(container, bg=container["background"]);
        self.p4 = Page4(container, bg=container["background"]);
        self.p5 = Page5(container, bg=container["background"]);
        self.p6 = Page6(container, bg=container["background"]);
        self.p7 = Page7(container, bg=container["background"]);
        self.p8 = Page8(container, bg=container["background"]);
        self.p9 = Page9(container, bg=container["background"]);
        
        topBar = Frame(container, bg=topBarColor, width=container.winfo_width() * framewidth, height=topBarHeight);
        topBar.place(x=0, y=0);
        
        self.p1.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1);
        self.p2.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1);
        self.p3.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1);
        self.p4.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1);
        self.p5.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1);
        self.p6.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1);      
        self.p7.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1);
        self.p8.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1);
        self.p9.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1);
        
        close= Button(topBar, text=u"\u2715", command= lambda: self.close(), bg=topBar["background"], bd=0, font = self.ft2, fg=fgColor, activebackground="#940000");
        close.place(x = topBar["width"] - topBar["height"], y = 0, width = topBar["height"], height= topBar["height"]);
        
        minim = Button(topBar, text="_", command= lambda: self.toicon(), bg=topBar["background"], bd=0, font=self.ft2, fg=fgColor, activebackground="#364969");
        minim.place(x = topBar["width"] - 2 * topBar["height"], y = 0, width = topBar["height"], height= topBar["height"]);
        
        label = Label(topBar, text=title, font=self.ft3, bg=topBar["background"], fg=fgColor);
        label.place(x = 5, y = 0, height= topBar["height"]);
        
        #event handlers so the window can be moved
        topBar.bind("<ButtonPress-1>", self.StartMove);
        topBar.bind("<ButtonRelease-1>", self.StopMove);
        topBar.bind("<B1-Motion>", self.OnMotion);
        
        label.bind("<ButtonPress-1>", self.StartMove);
        label.bind("<ButtonRelease-1>", self.StopMove);
        label.bind("<B1-Motion>", self.OnMotion);
        
        close.bind("<Enter>", self.closeEnterBG);
        close.bind("<Leave>", self.topBarButtonNormalBG);
        
        minim.bind("<Enter>", self.minimEnterBG);
        minim.bind("<Leave>", self.topBarButtonNormalBG);
        
        self.master.bind("<Unmap>", self.toiconify);
        self.master.bind("<Map>", self.todeiconify);
        
        ##################### page 1, intro ############################
        
        T1 = Text(self.p1, height = 8, width = 31, font=self.ft5, bg=bgColor, fg=fgColor, bd=0);
        T1.place(x=10, y=10);
        
        HelpButton = Label(self.p1, text = "help", background=bgColor, fg = hyperlinkColor, font = self.ft5, cursor="hand2");
        HelpButton.place(x=8, y=53);
        
        underlineFont = font.Font(HelpButton, HelpButton.cget("font"));
        underlineFont.configure(underline = True);
        
        HelpButton.configure(font=underlineFont);
        HelpButton.bind("<Button-1>", lambda x: self.clickHelp())
        
        T2 = Text(self.p1, height = 8, width = 31, font=self.ft5, bg=bgColor, fg=fgColor, bd=0);
        T2.place(x=53, y=55);
        
        
        T1.insert(END, "Welcome to the ELS Scorion tool. Click next to select what tool to use, or press\n");
        T2.insert(END, "to learn more about the tool.");
        
        T1.configure(state=DISABLED);
        T2.configure(state=DISABLED);
        
        nextButtonP1 = Button(self.p1, text = "Next", command=self.p2.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor);
        nextButtonP1.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight);
        nextButtonP1.bind("<Enter>", self.buttonEnterBG);
        nextButtonP1.bind("<Leave>", self.buttonNormalBG);

        ################## page 2, task picker #########################
        instrLabel = Label(self.p2, text = "Choose what tool to use", bg=self.p2["background"], fg=fgColor, font=self.ft5);
        instrLabel.place(x= 30, y = 10);
        buildGroupsButton = Button(self.p2, text = "Build Scorion groups", command=self.p3.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft5, activebackground=buttonPressedColor, activeforeground=fgColor);
        buildGroupsButton.place(x = 75, y = 48, width = 250, height = 2*nextprevButtonHeight);
        
        buildGroupsButton.bind("<Enter>", self.buttonEnterBG);
        buildGroupsButton.bind("<Leave>", self.buttonNormalBG);
        
        splitGroupsButton = Button(self.p2, text = "Split Scorion file", command=self.p4.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft5, activebackground=buttonPressedColor, activeforeground=fgColor);
        splitGroupsButton.place(x = 75, y = 120, width = 250, height = 2*nextprevButtonHeight);
        
        splitGroupsButton.bind("<Enter>", self.buttonEnterBG);
        splitGroupsButton.bind("<Leave>", self.buttonNormalBG);
        
        onlyFileButton = Button(self.p2, text = "Only create Scorion file", command=self.p5.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft5, activebackground=buttonPressedColor, activeforeground=fgColor);
        onlyFileButton.place(x = 75, y = 192, width = 250, height = 2*nextprevButtonHeight);
        
        onlyFileButton.bind("<Enter>", self.buttonEnterBG);
        onlyFileButton.bind("<Leave>", self.buttonNormalBG);
        
        possibleErrorButton = Button(self.p2, text = "Find errors in file", command=self.p8.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft5, activebackground=buttonPressedColor, activeforeground=fgColor);
        possibleErrorButton.place(x = 75, y = 264, width = 250, height = 2*nextprevButtonHeight);
        
        possibleErrorButton.bind("<Enter>", self.buttonEnterBG);
        possibleErrorButton.bind("<Leave>", self.buttonNormalBG);
        
        previousButtonP2 = Button(self.p2, text = "Back", command=self.p1.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor);
        previousButtonP2.place(x = nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight);
        
        previousButtonP2.bind("<Enter>", self.buttonEnterBG);
        previousButtonP2.bind("<Leave>", self.buttonNormalBG);
        
        
        ################## page 3, group builder ######################## 
        previousButtonP3 = Button(self.p3, text = "Back", command=self.p2.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor);
        previousButtonP3.place(x = nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight);
        
        previousButtonP3.bind("<Enter>", self.buttonEnterBG);
        previousButtonP3.bind("<Leave>", self.buttonNormalBG);
        
        courseIdWrap = Frame(self.p3, bg= self.p3["background"]);
        courseIdWrap.place(x = 10, y = 10, width = framewidth - 20, height = topBarHeight)
        
        self.courseVar = StringVar();
        self.courseVar.trace("w", lambda name, index, mode, courseVar=self.courseVar: self.firecallback());
        
        courseIdLabel = Label(courseIdWrap, text = "Course Id:", bg=self.p3["background"], fg=fgColor, font=self.ft4);
        courseIdLabel.place(x= 0, y = 0, height = topBarHeight);
        
        courseId = Entry(courseIdWrap, width= 45, bg=bg2Color, textvariable=self.courseVar,fg=fgColor, borderwidth = 0, font=self.ft4, insertbackground=fgColor, insertofftime= 500, insertontime= 500);
        courseId.place(x = 65, y = 0, height=topBarHeight);
        
        
        fileWrap = Frame(self.p3, bg =self.p3["background"]);
        fileWrap.place(x = 10, y = 44, width = framewidth - 20, height = topBarHeight);
        
        
        fileLabel = Label(fileWrap, text = "File:", bg=self.p3["background"], fg=fgColor, font=self.ft4);
        fileLabel.place(x= 30, y = 0, height = topBarHeight);
        
        self.fileVar = StringVar();
        self.fileVar.trace("w", lambda name, index, mode, fileVar=self.fileVar: self.firecallback());

        self.fileName = Entry(fileWrap, width= 36, textvariable=self.fileVar,bg=bg2Color, fg=fgColor, borderwidth = 0, font=self.ft4, insertbackground=fgColor, insertofftime= 500, insertontime= 500);
        self.fileName.place(x = 65, y = 0, height= topBarHeight);


        #TODO: drag files into the text field
        self.browse = Button(fileWrap, text="Browse", command=self.load_file, background=buttonColor, foreground=fgColor, bd=0, font=self.ft4, activebackground=buttonPressedColor, activeforeground=fgColor, anchor="center");
        self.browse.place(x=326, y=0, height = topBarHeight, width=60);
        
        self.browse.bind("<Enter>", self.buttonEnterBG);
        self.browse.bind("<Leave>", self.buttonNormalBG);        
        
        
        seperatorWrap = Frame(self.p3, bg = self.p3["background"]);
        seperatorWrap.place(x=10, y = 106, height = 2*topBarHeight + 2, width = framewidth - 20);
        
        optionLabel = Label(seperatorWrap, text="What seperator is used in the file?", bg=self.p3["background"], fg=fgColor, font=self.ft4);
        optionLabel.place(x = 0, y = 0, height = topBarHeight);
      
        optionList = [("Comma ( , )", ","),("Semicolon ( ; )", ";")];
        
        self.sepVar = StringVar();
        self.sepVar.set(optionList[0][1]);
        
        commaButton = Radiobutton(seperatorWrap, text=optionList[0][0], variable = self.sepVar, value=optionList[0][1], anchor="w", padx=5, bg=bg2Color, fg=fgColor, activebackground=bg2Color, activeforeground=fgColor, selectcolor=bg2Color);
        semiColonButton = Radiobutton(seperatorWrap, text=optionList[1][0], variable = self.sepVar, value=optionList[1][1], anchor="w", padx=5, bg=bg2Color, fg=fgColor, activebackground=bg2Color, activeforeground=fgColor, selectcolor=bg2Color);
        
        commaButton.place(x=260, y=0, height=topBarHeight, width = 120);
        semiColonButton.place(x=260, y = topBarHeight + 2, width = 120);
        
        
        optionLabel = Label(self.p3, text="Do you already have a Scorion File?");
        
        scorionCheckWrap = Frame(self.p3, bg = self.p3["background"]);
        scorionCheckWrap.place(x=10, y = 194, height=topBarHeight, width = framewidth - 20);
        
        self.checkVar = IntVar();
        
        scorionCheck = Checkbutton(scorionCheckWrap, text="Create a Scorion file?", var = self.checkVar, font=self.ft4, fg=fgColor, bg=bg2Color, bd=0, highlightthickness = 0, selectcolor=bg2Color, activeforeground=fgColor, activebackground= bg2Color);
        scorionCheck.select();        
        scorionCheck.place(x=210, y=0, height=topBarHeight, width = 170);
        
        
        self.goButton = Button(self.p3, text = "Run", command=self.combineFuncs, state=DISABLED,background=disabledButtonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=disabledButtonColor, activeforeground=fgColor, disabledforeground=fg2Color);
        self.goButton.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight);
    
        
        ################### page 4, split groups page ########################
        previousButtonP4 = Button(self.p4, text = "Back", command=self.p2.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor);
        previousButtonP4.place(x = nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight);
        
        previousButtonP4.bind("<Enter>", self.buttonEnterBG);
        previousButtonP4.bind("<Leave>", self.buttonNormalBG);
        
        scorFileWrap = Frame(self.p4, bg =self.p4["background"]);
        scorFileWrap.place(x = 10, y = 10, width = framewidth - 20, height = topBarHeight);
        
        
        fileLabel = Label(scorFileWrap, text = "Scorion File:", bg=self.p4["background"], fg=fgColor, font=self.ft4);
        fileLabel.place(x= 0, y = 0, height = topBarHeight);
        
        self.scorFileVar = StringVar();
        self.scorFileVar.trace("w", lambda name, index, mode, scorFileVar=self.scorFileVar: self.firecallback1());

        self.scorFileName = Entry(scorFileWrap, width= 34, textvariable=self.scorFileVar,bg=bg2Color, fg=fgColor, borderwidth = 0, font=self.ft4, insertbackground=fgColor, insertofftime= 500, insertontime= 500);
        self.scorFileName.place(x = 79, y = 0, height= topBarHeight);

        self.browse1 = Button(scorFileWrap, text="Browse", command=self.load_file1, background=buttonColor, foreground=fgColor, bd=0, font=self.ft4, activebackground=buttonPressedColor, activeforeground=fgColor, anchor="center");
        self.browse1.place(x=326, y=0, height = topBarHeight, width=60);
        
        self.browse1.bind("<Enter>", self.buttonEnterBG);
        self.browse1.bind("<Leave>", self.buttonNormalBG);
        
        errFileWrap = Frame(self.p4, bg =self.p4["background"]);
        errFileWrap.place(x = 10, y = 44, width = framewidth - 20, height = topBarHeight);
        
        
        errLabel = Label(errFileWrap, text = "Error File:", bg=self.p4["background"], fg=fgColor, font=self.ft4);
        errLabel.place(x= 0, y = 0, height = topBarHeight);
        
        self.errFileVar = StringVar();
        self.errFileVar.trace("w", lambda name, index, mode, errFileVar=self.errFileVar: self.firecallback1());

        self.errFileName = Entry(errFileWrap, width= 36, textvariable=self.errFileVar,bg=bg2Color, fg=fgColor, borderwidth = 0, font=self.ft4, insertbackground=fgColor, insertofftime= 500, insertontime= 500);
        self.errFileName.place(x = 65, y = 0, height= topBarHeight);

        self.browse2 = Button(errFileWrap, text="Browse", command=self.load_file2, background=buttonColor, foreground=fgColor, bd=0, font=self.ft4, activebackground=buttonPressedColor, activeforeground=fgColor, anchor="center");
        self.browse2.place(x=326, y=0, height = topBarHeight, width=60);
        
        self.browse2.bind("<Enter>", self.buttonEnterBG);
        self.browse2.bind("<Leave>", self.buttonNormalBG);
        
        self.goButtonP4 = Button(self.p4, text = "Run", command=self.combineFuncs2, state=DISABLED,background=disabledButtonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=disabledButtonColor, activeforeground=fgColor, disabledforeground=fg2Color);
        self.goButtonP4.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight);
        
        ################### page 5, only create groups page ##################
        previousButtonP5 = Button(self.p5, text = "Back", command=self.p2.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor);
        previousButtonP5.place(x = nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight);
        
        previousButtonP5.bind("<Enter>", self.buttonEnterBG);
        previousButtonP5.bind("<Leave>", self.buttonNormalBG);
        
        courseIdWrap2 = Frame(self.p5, bg= self.p5["background"]);
        courseIdWrap2.place(x = 10, y = 10, width = framewidth - 20, height = topBarHeight)
        
        self.courseVar2 = StringVar();
        self.courseVar2.trace("w", lambda name, index, mode, courseVar2=self.courseVar2: self.firecallback2());
        
        courseIdLabel2 = Label(courseIdWrap2, text = "Course Id:", bg=self.p5["background"], fg=fgColor, font=self.ft4);
        courseIdLabel2.place(x= 0, y = 0, height = topBarHeight);
        
        courseId2 = Entry(courseIdWrap2, width= 45, bg=bg2Color, textvariable=self.courseVar2,fg=fgColor, borderwidth = 0, font=self.ft4, insertbackground=fgColor, insertofftime= 500, insertontime= 500);
        courseId2.place(x = 65, y = 0, height=topBarHeight);
        
        
        fileWrap2 = Frame(self.p5, bg =self.p5["background"]);
        fileWrap2.place(x = 10, y = 44, width = framewidth - 20, height = topBarHeight);
        
        
        fileLabel2 = Label(fileWrap2, text = "File:", bg=self.p5["background"], fg=fgColor, font=self.ft4);
        fileLabel2.place(x= 30, y = 0, height = topBarHeight);
        
        self.fileVar2 = StringVar();
        self.fileVar2.trace("w", lambda name, index, mode, fileVar2=self.fileVar2: self.firecallback2());

        self.fileName2 = Entry(fileWrap2, width= 36, textvariable=self.fileVar2,bg=bg2Color, fg=fgColor, borderwidth = 0, font=self.ft4, insertbackground=fgColor, insertofftime= 500, insertontime= 500);
        self.fileName2.place(x = 65, y = 0, height= topBarHeight);

        self.browse3 = Button(fileWrap2, text="Browse", command=self.load_file3, background=buttonColor, foreground=fgColor, bd=0, font=self.ft4, activebackground=buttonPressedColor, activeforeground=fgColor, anchor="center");
        self.browse3.place(x=326, y=0, height = topBarHeight, width=60);
        
        self.browse3.bind("<Enter>", self.buttonEnterBG);
        self.browse3.bind("<Leave>", self.buttonNormalBG);        
        
        
        seperatorWrap2 = Frame(self.p5, bg = self.p5["background"]);
        seperatorWrap2.place(x=10, y = 106, height = 2*topBarHeight + 2, width = framewidth - 20);
        
        optionLabel2 = Label(seperatorWrap2, text="What seperator is used in the file?", bg=self.p5["background"], fg=fgColor, font=self.ft4);
        optionLabel2.place(x = 0, y = 0, height = topBarHeight);
      
        optionList2 = [("Comma ( , )", ","),("Semicolon ( ; )", ";")];
        
        self.sepVar2 = StringVar();
        self.sepVar2.set(optionList2[0][1]);
        
        commaButton2 = Radiobutton(seperatorWrap2, text=optionList2[0][0], variable = self.sepVar2, value=optionList2[0][1], anchor="w", padx=5, bg=bg2Color, fg=fgColor, activebackground=bg2Color, activeforeground=fgColor, selectcolor=bg2Color);
        semiColonButton2 = Radiobutton(seperatorWrap2, text=optionList2[1][0], variable = self.sepVar2, value=optionList2[1][1], anchor="w", padx=5, bg=bg2Color, fg=fgColor, activebackground=bg2Color, activeforeground=fgColor, selectcolor=bg2Color);
    
        commaButton2.place(x=260, y=0, height=topBarHeight, width = 120);
        semiColonButton2.place(x=260, y = topBarHeight + 2, width = 120);
        
        self.goButtonP5 = Button(self.p5, text = "Run", command=self.combineFuncs3, state=DISABLED,background=disabledButtonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=disabledButtonColor, activeforeground=fgColor, disabledforeground=fg2Color);
        self.goButtonP5.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight);
        
        
        ################### page 6, progress page ###########################
        self.cancelButton = Button(self.p6, text = "cancel", command=lambda:sys.exit(), background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor);
        self.cancelButton.place(x = nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight);
        
        self.cancelButton.bind("<Enter>", self.buttonEnterBG);
        self.cancelButton.bind("<Leave>", self.buttonNormalBG);
        
        self.progressLabel = Label(self.p6, text = "Working, this might take a couple of minutes...", bg=self.p6["background"], fg=fgColor, font=self.ft1)        
        self.progressLabel.place(x=10, y=36);
        
        
        #TODO: make the progressbar actually progress to the things that are done
        style = Style();    
        style.theme_use('alt')
        style.configure("els.Horizontal.TProgressbar", background=fgColor);        
        
        self.progress = Progressbar(self.p6, orient=HORIZONTAL, length = framewidth - 20, mode="indeterminate", style="els.Horizontal.TProgressbar", maximum=40);  
        self.progress.place(x=10, y=10);
        self.progress.start(17);
        
        self.closeP6 = Button(self.p6, text = "Close", command=self.close, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor);    
        
        
        ################### page 7, error page ###########################
        #TODO: implement full stacktrace instead of only 2
        #TODO: or: make a log file of the stacktrace that can be "downloaded" when clicked
        #TODO: error page is not working correctly anymore; errors are being cut off
        self.errorLabel = Label(self.p7, text = "Something went wrong, try again or contact Cas", bg=self.p7["background"], fg=errorColor, font=self.ft1);
        self.errorLabel.place(x=36, y=10);

        self.errorInfoLabel = Label(self.p7, text = "Error Info:", bg=self.p7["background"], fg=fgColor, font=self.ft1);
        self.errorInfoLabel.place(x=36, y=50);

        self.stackTraceStringVar1 = StringVar();
        self.stackTraceStringVar2 = StringVar();
        
        self.stackTraceLabel1 = Label(self.p7, textvariable = self.stackTraceStringVar1, bg=self.p7["background"], fg=errorColor, font=self.ft1, wraplength = 350, justify=LEFT);
        self.stackTraceLabel2 = Label(self.p7, textvariable = self.stackTraceStringVar2, bg=self.p7["background"], fg=errorColor, font=self.ft1, wraplength = 350, justify=LEFT);
        
        self.stackTraceStringVar1.set(self.getStackTrace()[0]);
        self.stackTraceStringVar2.set(self.getStackTrace()[1]);
        
        self.stackTraceLabel1.place(x=36, y=70);
        self.stackTraceLabel2.place(x=36, y=110);
        
        self.backToMenu = Button(self.p7, text = "Back to menu", command=self.backtomenu, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor);
        self.backToMenu.place(x = nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight);
        self.backToMenu.bind("<Enter>", self.buttonEnterBG);
        self.backToMenu.bind("<Leave>", self.buttonNormalBG);

        self.closeP7 = Button(self.p7, text = "Close", command=self.close, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor);
        self.closeP7.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight);
        self.closeP7.bind("<Enter>", self.buttonEnterBG);
        self.closeP7.bind("<Leave>", self.buttonNormalBG);
        
        
        ################### page 8, find error page ###########################
        previousButtonP8 = Button(self.p8, text = "Back", command=self.p2.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor);
        previousButtonP8.place(x = nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight);
        
        previousButtonP8.bind("<Enter>", self.buttonEnterBG);
        previousButtonP8.bind("<Leave>", self.buttonNormalBG);
        
        checkErrFileWrap = Frame(self.p8, bg =self.p8["background"]);
        checkErrFileWrap.place(x = 10, y = 10, width = framewidth - 20, height = 3*topBarHeight);
        
        
        checkErrLabel = Label(checkErrFileWrap, text = "File to check for Errors:", bg=self.p4["background"], fg=fgColor, font=self.ft4);
        checkErrLabel.place(x= 0, y = 0, height = topBarHeight);
        
        self.checkErrFileVar = StringVar();
        self.checkErrFileVar.trace("w", lambda name, index, mode, checkErrFileVar=self.checkErrFileVar: self.firecallback3());

        self.checkErrFileName = Entry(checkErrFileWrap, width= 45, textvariable=self.checkErrFileVar,bg=bg2Color, fg=fgColor, borderwidth = 0, font=self.ft4, insertbackground=fgColor, insertofftime= 500, insertontime= 500);
        self.checkErrFileName.place(x = 2, y = 25, height= topBarHeight);

        self.browse4 = Button(checkErrFileWrap, text="Browse", command=self.load_file4, background=buttonColor, foreground=fgColor, bd=0, font=self.ft4, activebackground=buttonPressedColor, activeforeground=fgColor, anchor="center");
        self.browse4.place(x=326, y=25, height = topBarHeight, width=60);
        
        self.browse4.bind("<Enter>", self.buttonEnterBG);
        self.browse4.bind("<Leave>", self.buttonNormalBG);
        
        self.goButtonP8 = Button(self.p8, text = "Run", command=self.p9.lift, state=DISABLED,background=disabledButtonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=disabledButtonColor, activeforeground=fgColor, disabledforeground=fg2Color);
        self.goButtonP8.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight);
        
        ################### page 9, find error results ###########################
        previousButtonP9 = Button(self.p9, text = "Back", command=self.p8.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor);
        previousButtonP9.place(x = nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight);
        
        previousButtonP9.bind("<Enter>", self.buttonEnterBG);
        previousButtonP9.bind("<Leave>", self.buttonNormalBG);
        
              
        #testing
        self.checkErrFileName.delete(0, END);
        self.checkErrFileName.insert(0, r"M:\ud\os\ssc\imos\bbsup\@ new folder_Surfdrive\7. Scorion\Vakmappen 171804\46597-171804\group_import_no_TAs.txt");
        
        self.errors = errorChecker(self.checkErrFileVar.get());
        self.croppedErrors = self.errors[0:7]
        
        if (len(self.errors) > 0):
            Label(self.p9, text = "Found %d possible errors, on the following lines:" %len(self.errors), fg = fgColor, bg = bgColor, font = self.ft1).place(x=16, y=12);


            openFile = Button(self.p9, text = "Open file", command=lambda: self.clickOpenFile(), background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor);
            openFile.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight);
        
            openFile.bind("<Enter>", self.buttonEnterBG);
            openFile.bind("<Leave>", self.buttonNormalBG);            
            
            self.drawErrors();
            
        else:
             Label(self.p9, text = "Found no errors", fg = fgColor, bg = bgColor, font = self.ft5).place(x=10, y=10);    
                
                
        ################### finally, show page 1 to start ################
        self.p1.show();
示例#30
0
'''

Chapter 7

Handling Widget Resize


'''


from tkinter import Tk, Label, Pack

root= Tk()

label  = Label(root, text = 'I am a Frame', bg='red')
label.pack(fill='both', expand=True)


def on_label_resized(event):
    print('New Width', label.winfo_width())
    print('New Height', label.winfo_height())


label.bind("<Configure>", on_label_resized)

root.mainloop()
示例#31
0
class Button_(Widget_):

	def __init__(self, parent_frame, x, y):
		Widget_.__init__(self, parent_frame, x, y)
		self.label_bg, self.label_fg = 'grey', 'white'
		self.hover_bg, self.hover_fg = None, None
		self.label = Label(self.widget_frame, bg=self.label_bg, fg=self.label_fg)
		self.label.grid(row=0, column=1, ipadx=5, ipady=10)
		
	def get_info(self):
		return self.label.cget('text')

	def set_hover(self):
		def set_hover_bg(event):
			self.label.config(bg=self.hover_bg, fg=self.hover_fg)
			self.img.config(bg=self.hover_bg, fg=self.hover_fg)

		def remove_hover_bg(event):
			self.label.config(bg=self.label_bg, fg=self.label_fg)
			self.img.config(bg=self.label_bg, fg=self.label_fg)

		if hasattr(self, 'img'):
			self.widget_frame.bind('<Enter>', set_hover_bg)
			self.widget_frame.bind('<Leave>', remove_hover_bg)
		else:
			self.widget_frame.bind('<Enter>', lambda event: self.label.config(bg=self.hover_bg, fg=self.hover_fg))
			self.widget_frame.bind('<Leave>', lambda event: self.label.config(bg=self.label_bg, fg=self.label_fg))

	def settings(self, **kwargs):
		''' all setting changes '''
		
		if 'label_bg' in kwargs:
			self.label_bg = kwargs['label_bg']
			self.label.config(bg=self.label_bg)
		if 'label_fg' in kwargs:
			self.label_fg = kwargs['label_fg']
			self.label.config(fg=self.label_fg)
		if 'text' in kwargs:
			self.label.config(text=kwargs['text'])
		if 'font' in kwargs:
			self.label.config(font=kwargs['font'])
		if 'hover_bg' in kwargs:
			self.hover_bg = kwargs['hover_bg']
			self.hover_fg = self.label_fg if self.hover_fg == None else self.hover_fg
			self.set_hover()
		if 'hover_fg' in kwargs:
			self.hover_fg = kwargs['hover_fg']
			self.hover_bg = self.label_bg if self.hover_bg == None else self.hover_bg
			self.set_hover()
		if 'command' in kwargs:
			self.command = kwargs['command']
			self.label.bind('<Button-1>', lambda event: self.command())
			if hasattr(self, 'img'):
				self.img.bind('<Button-1>', lambda event: self.command())
		if 'image' in kwargs:
			self.img_path = kwargs['image']
			self.picture = Image.open(self.img_path)
			self.image = ImageTk.PhotoImage(self.picture)
			self.img = Label(self.widget_frame, bg=self.label_bg, fg=self.label_fg)
			self.img.grid(row=0, column=0, ipadx=5, ipady=5, columnspan=2, sticky=W)
			self.img.config(image=self.image)
			self.set_hover()
			if hasattr(self, 'command'):
				self.img.bind('<Button-1>', lambda event: self.command())
		if 'image_resize' in kwargs:
			self.picture = self.picture.resize(kwargs['image_resize'], Image.ANTIALIAS)
			self.image = ImageTk.PhotoImage(self.picture)
			self.img.config(image=self.image)
		return
示例#32
0
class CBUTTON(LabelFrame):
    '''
        Widget de clase Boton con texto en sus extremos depende de imagenes externas
    '''
    def __init__(self,
                 master,
                 row,
                 column,
                 Ltext='true',
                 Rtext='false',
                 command=None):
        super().__init__(master)
        self.row = row
        self.column = column
        self.LT = Ltext
        self.RT = Rtext
        self.Rtext = StringVar()
        self.Ltext = StringVar()
        self.command = command
        self.state = False
        self.config(bg=master['bg'], padx=2, pady=5)
        self.grid(row=self.row, column=self.column)
        self.imagePath = StringVar()
        self.imagePath.set(btnoffimg)
        self.button = Label(self)
        self.button.config(cursor='hand2', bg=master['bg'])
        self.button.bind('<Button-1>', self.onClick)
        self.button.bind('<ButtonRelease-1>', self.onRelease)
        self.button.grid(row=1, column=1)
        self.leftTextlabel = Label(self)
        self.leftTextlabel.config(bg=master['bg'], fg='white')
        self.leftTextlabel.grid(row=1, column=0)
        self.rightTextlabel = Label(self)
        self.rightTextlabel.config(bg=master['bg'], fg='white')
        self.rightTextlabel.grid(row=1, column=2)
        self.updatebutton()
        self.swapState = (lambda x: (x == False))
        self.swapImage = (lambda x: (btnoffimg) if x else (btnonimg))

    def onClick(self, event):
        '''
            actualiza el estado del boton
        '''
        self.imagePath.set((self.swapImage)(self.state))
        self.state = self.swapState(self.state)

        self.updatebutton()

    def onRelease(self, event):
        '''
            ejecuta la acción
            dada por la instancia de clase
            en el parametro command al soltar el click
        '''
        if self.command is not None:
            self.command()

    def updatebutton(self):
        '''
            actualiza la imagen del boton
        '''
        self.Ltext.set(self.LT)
        self.Rtext.set(self.RT)
        self.rightTextlabel.config(textvariable=self.Rtext)
        self.leftTextlabel.config(textvariable=self.Ltext)
        self.btn_image = PhotoImage(file=self.imagePath.get())
        self.button.config(image=self.btn_image)
class Installer(Frame):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.master.title("SAS University Edition Install Tool")
        self.pack(fill=BOTH, expand=True)
        self.columnconfigure(1, weight=1)
        self.columnconfigure(2, pad=7)
        self.rowconfigure(3, weight=1)
        self.rowconfigure(5, pad=7)

        ### Loading the image ###
        base64_image = b'R0lGODlhgACAAHAAACH5BAEAAP8ALAAAAACAAIAAhwAAAABSnABSjO9jIYQQSt5SGaUQUu9KGYQZGaUhGe9SMVopEFKlzlIxOpwQENZKc3sIGcUZc+YxSu+EEFJjEFK9EBljEBm9EMUZIe9Sc+97UsUxKRlanMUpSoSEGYTOGc6EnM7OnM6E3oTOnISEnHsIMVLm7xnm71Kt7xmt71LmzhnmzhmtzkKtpULmpQjmpQitpe/mWu+9Ga0Zc87mWs69GQBChKUQMc5KlO9KlOYZc0pjc84ZlO8ZlOYQSsVSENaEEMUZWu+1Wpyl3lqlpa1SnK0ZnM5S74RS71KUEFLvEBmUEBnvEM4Z74QZ74QZe4RSe85SxYRSxc4ZxYQZxe8QGeYxGYTF3loIEFJ75lKMcxmMc1JjMVK9MRljMRm9MVK9cxm9c1Ja5lKMUhmMUlK9Uhm9Uq17WsXm3u/v3u9aUq3vWqXv3q2lGa3vGe/vGe/vnISlWoTvWoSlGYTvGUqEtc6lnM7vnM6l3oTvnISlnHuE3u+EnM69Wu+E3qXOnKWEnM7vGc5KWqU6Ge+llPeUa9aEMaU6SsVSOveUUqXF1mPmpSnmpSmtpUp7nHs6SkpalIQ6GRlac1JaUiE6QqVSc+9S71Lvc1o6c6VS71KUMVLvMRmUMRnvMe8Z76UZ7xnvcxl77yE6rYQZnNaUY4RSnO9SxaVSxe8ZxaUZxRl7xYRaGSEQSlJjvRljUlLvUhnvUhla7xlaxUI65gg65kI6rQgZe0IQcwgQrUIQ5ggQ5kIQre9zMZwQIcXF3gBjnCF7nO/FnGMIMXulxe+l3qXvnKWlnDEQEKVaGTExEFoAIYRaSoQZOhAQEBA6EKVaSgAZGTo6cwA6pSFCc++MMQAQQgAxStZzWkoIOmM65ik65mM6rSkZe2MQcykQrWMQ5ikQ5mMQre+EY8UQOq2la4Tv76WE7+/O763Oa62EKa3OKYSEa4TOa62lSoTvzqWEzu/Ozq3OSq2ECK3OCISESoTOSqUhMXul78UQCMUpEKXF7/djCAAAEABSpQhSnAAAAAj/AP8JHEiwoMGDCBMqXMiwocOHECNKnEixosWLGDNq3Mixo8ePIEOKHEmypMmTKFOqXMmypcuXMGPKxIggQU0ENzcMQmQvgc+aP30mGKRyg9ENP4wmRWoUUdIfTqH+kEpyUIKeV69uQCRhK4asPe1hCLsBA8oCaAso2DDghwK3cNUOmMtLroIBCkhi7dlr0Ia1iKwgMpoAQ68NPnti0IlSgRUJbxUUQKTgAGW1bwfwGlCgrucfJIX6NLr2b1PEYq9+RWwUpdsNamGvRdsV7Wa6BThL5qU3Us8NEgZvHd4VdeGeNxK0PqlBjVq0kp+n9TxXs+YfdfUmHtx1bXevhQel/x67GKUGzhJiS0aEuXP195rVkoxkszDS4FsFAx+clbXyDSjxUtlzllkhGVvv8YIIXZzxAtpIWNU0nGD6AbZYL6thqFxjBUhwgAIefggbL4bAV1eJ1fEGoU3JFcbdYN4V0IFR5ImFWGOVSXbAc3dVV6Ih7qXIWWhAIdCLcqUBBlxwX2EwyGoJnCWZhwqAWIAaGlCj2T50cfmefCNdhUCLCfQC44wgqiGBIBuIJdYNN57k2IA68qKBEFluZsg+KJbo4FtVHcmiTxicKQFkh3YV3gaH4agWlQpokEghk2rAyz63zcVjXhD2UtORnx6lZnCHKtDBkzZGKadaB+w4gKSUUv+aSCK86BmfZICG6dMNn5aZQAeHchWsIBIsVtiGJ2FWpQJqTOpsrLROoGlkYIo0JlDJ9SqsmqOq0cFxcZoEWYedPWtuIhqchxePD4pkFai++nRksIeOWhoGYwUIWZXiiGNurEJQqsYPA7CHq169HtmLPYImwJWawh4KZ2EoqVEllrA6+6w4hXSsgW1qtRuSkTb1BFQCyR2WqASjdnVhY4iogXG6kwLc8c3iqKFbtSPj1GvKQh0W88qHlmWWnGrYmW6z/t5ZCMc3d5yIc3iJDJLPvTQsaIu9AEt0V+OoahKzzaVbds1Rp01KXVUSiXWZfO2aQD5fF320SWUvbXa6aff/fc1mVn+EUy8O1Ocrwz6FveTXYpdkNsYzdwx13x53RpLPNnmqsNwYjINB3Yeat7fZ4mgQtTiEdMzH6RoYcnnm9WFrn9GL1Y1Sv5Dz/bTklD8tqYrWan5tmQqXFfY4G4yTqA6JosQHx6WjW4jppu/eN83oVnVT5p76irznyddO9O3iPN9v2lBDTUj0kqKrwetZk3zTwoR2XpYEGWRwqP7Oqx+16f6yXvsk1b5EuM1XJBPUwoziuQ5kgA/6O5QOUKK6QgSjb5Ob1awIiK7sjQQBEPCUkUZYpk8dBgMOhGD+9KcGCqYuGEIIxgX7psEN1jBLlwPh9gy3ua498IEqlMAE/0+yOhgGgxAxvFkNEyGEDrqvgzmEgM9wgrJe+aQDavhhDsSRg/yhxIiEgGEYAyarJS6RgFHECQQc0D2U7coeGxDEAyCoQi+exIJJlGEhAsZEMzaRg+m63BqnOMI2/moDM8riCjPwAArGMIZIFEITazhJM2owihCQ4hSPlJwZeRKLK1RDI09ywSRW0pKnJCA1DPhBNWKNikY6BCI9aY8OEOsBuEQJEpHYRz+aMUvAfF9FBCCAABjzmMi0gQCmwUxmRsOZ03jmM6exg2lA4pnXhEQ2i4nMbnrzm+Dspg0CIABHOAISWoDEDtC5gx1ooZ3pdGc757nOdnIgnMe0AUK4af/McQZgnP4MwC/ISVBvDhSZvzioN/3J0H/206EObahEHxpQcvIznArtJj+5CVCKGjMhBf1mMblJUnyWtKT4TKlKjzlSlhrzoi4NJ0rBuRCCtjSkBf3FRgeK0oue1KYFvalQg0rUm8YUpi9FZk95qtSkFpMhTSVqTEPKzYPOFKdUjWpSp4pVoB6VnDp1qkClKtatBsAhWXWpAAYa1rVmtapr5YBVmbpVo9q1rEDlZ1sPGlazWtWYbDWqWSES0rAeFBiKUMQw6sDSxZIUGMNIbB04MAwGoBSy9yQnZIHxUsomFbIKrUMdilkHywpUAJuNrGqv4AjRFpMDDEisIhjAAQH/UDaxwwCsXQUAkZ8SlAOKmGwdhnFQDqBBEcWdLQeGC4zS1haZw0jDaAPQjzqkQRGA5QAbMhsARaBhugKowxXA6gsGGBO4wq2DZCc7jNz+QhGs5QBiGTuMK3CAssAoaV8lAtaYqjeqlQ2uZn3B3QDct6TzVUQ/jFkHfQg4AMDwxUsT/FIGDGGk6r3nMIaQTwbk1piVFcCG+XlP4xa4ruSkyFUjXIe+GlgRy8WuQH3RYn9u1Jge7kdwSRtcX3AWGNsFMW31wdnwKoKf7UXsc0Gc22K2lwM+RqpiuYtUixDUxepVbIVzC1zOBiDLtJ0qcDX84f9uGMK+WPCYA9BeJicV/7g0dmmbhRzhzN4UuIr1MlifOkwUnxcYV4BxAMoLDMpy+M+JvWcxw1oHHy/XxxCWsSL2AAx9cMAGwyDyctFw6f8iWR8ZtYGHCfpkTmv0mKoYBqRhWpFTh7TLdThuYn1hamQ++MredfAV0JDb/9pgvr74BZxlW94AjDqp6jXqnNk8DB0z1qstXXZLVSzWgS73vAQOLgcWHIAhMOAXjjjvjguaYWOKotIxPi8DaP0L9S64H9WFcbKt+t9kjtrJvR73l1s82XHO1qwfjYhL/4rY9iq23MdUb6UNfg+NVrabwa3DoV9M4Cs8W9zNRcMQAs0AG4h3nEj+MJvNa2zF1lcRhf/meGQVfVqbCvzGJBZtHfoh7Jhydrl1KDRQhf1cbt4XwgWtLs+DKov71sERwHBEiTPL1J+/9p7jXO5iM+sPyE5Wq8d8CFkBDk6ksjyjWOfqqZEKWLymtKL5LKtRGwLTtpZ9qoK9cV7rqlDfetWkGW2p3s26d2+6dawphupIXex2uf9V7lhdtFq5qviW95SohoW72J3q4r4vhOyC5TtOh0r5xUse5pL/qk3nqtvFIxWlCgWpWH3a8sAitO2lP/wx93rl2fv0ry+tvEgZv3u4ev6sB9k5Sa3azOJLAhLFT340JDHNaE4D9FLtO+fvulZ1UrOd16en9rdvz6C6naAWEQb/FsaPBSlq5ShGmZFR4ITIo6CEGoawFIkG8CNDGEIG968BNWpAIvv7HwiChBP2MIBiYT+dYz/j8D3IgwHJYR6bUSvWMReYwgsTwAvUQA0VOAETsA8bWIF6QYAgSDtlET4bACfK4wOM0jgkQQ210oLSQoEDgIEWmIEpUiseOBK+MYCHMICDgDzG84Pj4AMSIIQ+8C32ECAteCkDIC1LaIEU2IKYsiXVQRKPAIIEiC+MgoXKc4JDOITlcRIsyIIQyCAyKIMvyCUPOAAkwQz2sIM62CY/aA/KgwFESITJAyAnkYQXWIFNWIEUyIIRuBlecjlWSIDjMIDfI4R0OIQbYAAL/zMO7+eEFYiBYiiDTygtmBKFQzISC0CAbogyJdgmcEKHKPg9CwMnAVKJZuiEMziGmbIZBUASnWgPzIAAtcgMoHgDyHMDwNI5HRA2A4iKYGiDZTiJrIiBW/KAXMIpItEAUlSLCYCLbAgn9mCCCfiLHXAD1VgWSNiKExCGdsILtJIp8LGJIiF+uGiL1yKHcrgBQRAEHYCNvxg+EtAYemiMYtiCrXIAQjIAByCLwoATtxiN2iiH7ygBQTAO2JiAG2AFd1MSFsMLSeOEYjiOiZAjBxAimgI8ITF+EFCLnsIMR2IPQaADJRkEEqCQCmkAcmgFeGgStZI0CqCH8seCH2IF+/8YIpVBElhwDM9oi9FIkkHgAw9wku9YjXKYAD4AiXkYkUmjBgeQhPKXIwbSKlWphiOhDAsQkLbYC2w4gCeJkDrQAUjJkgZwFUcIkzGJF3dhBZrRgpVRlTr5If/IiR7JK2VZSyapA0V5AzfAhsygjUFgAMxgEtfwlDMJlVT5lq3iGAWwIxrJjB15DMKwAH9phQZwkuNwAwEZmEgZAYNpmGUjkf54kzlSJaaJk425IyWxAFggDF9JAPbAkiTZAUFQAghQAs84mxGgA75pEjmzNJVxkwNQlbWCK61CJR+ClSMhfliAALQIgrTJDBAQkLrJDJnpmxGwnSRxDRoQnDJJl6f/KSACMiX76I+SGRLiV52AaQ+ySYvMIAyZJEUlcAMlqQO9+ZsjgSVqkDM5A5UhIgEMApfouZwmUZnjB50FSQDMUIsQUAILUAIlwAxBwAM94Jv42QM8IBLe2Z8e+p+lGZUz2YJvOReNaRKvCQGv+ZWB2aATqpu4aQA50AMamp8XKhIZoAbX4J9Z9J85ApfkmYSbkZ4diQULoKIQ4J4N2qC5CaMGQKMzSqM6wAM6oKEg8QAZIA45yqMeGpECUqLkeYEQeBLjV5mwyaTMMKENKps6EKU02gMlKaUb6hHXwEgg0KV4WiVC+oAUSQ0ooQxlWn4u+pe3aAAPYKE9MKM5EAEGSJCZM1qUHZE/14ADWvqhXbos5DmiFGmBKOGaHll+auqiBhABOJCoNFqqM2AABNCo+JmqG5EBkyoOlEqpWSozFrMsemodtXKBYf+YEim6ni+appmJA4r6pkGwpGaZqo2KEViKA1k6q7KqpTlTJYiCqbvapypBftWpokzaqMTaA6VaqjlAmMxAAObKDKQ6A4dgABaBpV0ErTjwACCQo7e6LBm5LG8Jjhx5oNoKrN6qqDmgqEFAACXAoOU6AzjAAwk7AwwrEV30sBkAAlgKAnX6rBZTrcsCGVEppmK6EuX3muUnnwYgrjnAAyWbAzhAsEtarhWasAqLA5UQATMQAQwxm4KQAQ8bsBmAAxUrsQ8gCIKAq9WakQayD+DIEhAAqOWnDJmEsCcbsCUbAeZqsKvqsgmbsKSartsps0EwA4O5rrM5rBCrs/P6ANf/8LNyhLHUegA4KQFu2ass8bGvOaGZabKJarI4oKrlyqCrygMKqwNXm644QKqVEASgCZqDOZtg664427iU+rNqALTEojMaCxkGYgU46Zb76quAmknY2agPEK4zOgPlqreyqbCoq7BZiwMIe7gzIAheC7ZmaQCCALWNmwNoC7S5Syxri7lu6xjpEYsuUaYlELaNGgTimrKq+ghTSwAJe6glq7AzwAMIi7Bd+44z+7Usua5BMLYPIAEd8LO7K7kgwraO+RgFgLkxIZ/YSQDrmqrI2wOkSwCPoKoG8ATIiwNXywOHuroz67Wwi72yO4C0i7sm+Y7wKLlrQixAmx6P4btW/5C+9RgTtkiLs9uoXju1y8ug+vuy+ju4MWsEhAuaXjuzHTC79uC1RomQKImSkvvCbNIB6Xu+6DsT9lu/n0uYDWCuzLuqBICw+luyWPsEBnAIDJu9r/uOhTsDtlkJuKS/CCkI72hLCdzAQKt+RuG26Ku+M/EP9WvBX0ywwmCuBsC8BgDEH4yylaCuT3AIbTwDhSvCW/vEU/oAgFuUBznFKLkmD4AI6scTg0EhBtLFA+GeLCmbBCAMiqzIe3sIRtDBH8y6P+y+M/DD2+nEc8wDO9umOMCX8EjFHTCWktt+PAGH+fEYL9nFh4CdrJzIwlACY6zIP5zGV8u69fsIT/DDj/8QAQ+wtVvbySj7ADkAuC08xbb5yVsBR4cwI6WcHqlMyO7LytiwyIucyM7rwR18v+7rvkS8nTwQAZXwzaF7qG0aup4MLKBMgEcxGH4BRzrxzIT8D6xcAsqgDIsMy2NcsASgsOCqv7dMxE/ADHDsy3PcAzsLvYAbj1OsjQVpD6VcS8nME/F8EO45zcJgz/b8ys07xghLvWVMurfstYMLzts5uMQKuIBrwGSJlJc5gEYhS6W8AYcw0QmhyBlt09Q8tWNMv2Rcv0RsxL7cy73ZyfGKu0V5CAwdnV6pzjE90zStEPR80VJNzbCs0+a6w3z7wzMbswSNS/j5jkUpCAagjZ7/KZK0aMqy9NQMgdMYrcgW/cqxLKGJXLANgJ1GfMaPoK5eGwFSjEtBUJQMM40KCp3KzBhq3RA4ndjC8NYF+8rxuberWsSNqqqHIAh8jbigKdb2MCaAuTCeiQiHDRGLnNE3Tc1wPddjvK71u81GbLhBYNlSLMVkyYZeiTLSGNoTYdpTrcj4zNuvXLBFvM2qmsKx/bpJLAjViIuXWZi4bRHK8NalXZ29LZurXcbWbcRS/Nqv/bosydlp2dwYYdqwjM/xyZ4+fAir6p7rWtzZHduACd4ecc9wndPRbN2rfQjvyN5d69TwLRIl4IyOfaaUTZjWbQCFW7j83d8twQyPsLLMF63gEB7hEj7hFF7hFn7hGJ7hGr7hExEQADs='
        analyticsphoto = PhotoImage(data=base64.b64decode(base64_image))
        self.analytics_u_photo = Label(self,
                                       image=analyticsphoto,
                                       justify=CENTER)
        self.analytics_u_photo.image = analyticsphoto
        self.analytics_u_photo.grid(row=0, column=1, sticky=N)

        self.messagelabel = Label(
            self,
            text=' Welcome to the SAS University Edition Install Tool!\n\n' +
            ' Verify that you have Oracle VirtualBox installed and that you downloaded the\n'
            +
            ' SAS University Edition vApp and Oracle VirtualBox before running the'
            + ' installer.\n\n',
            borderwidth=5,
            relief="ridge")
        self.messagelabel.grid(row=1,
                               column=0,
                               columnspan=4,
                               rowspan=4,
                               padx=7,
                               sticky=N + W + E + S)

        self.quit_button = Button(self, text="Quit", command=self.exit)
        self.quit_button.grid(row=5, column=0, padx=5, pady=5)

        self.action_button = Button(self,
                                    text="Next",
                                    command=self.first_action_button_clicked)
        self.action_button.grid(row=5, column=3, padx=5, pady=5)

        self.user = os.getlogin()
        self.base = r"C:\Users\{}".format(self.user)
        self.downloads = self.base + r"\Downloads"
        self.shared_folder = self.base + r"\Documents\SASUniversityEdition\myfolders"
        self.ova_filename = ''
        self.checklist = [
            'SAS', 'University', '"SAS ', '"SAS University Edition"',
            'SAS University Edition', 'SAS University Edition_1',
            'SAS University Edition_2', 'SAS University Edition_3'
        ]

    def exit(self):
        '''
        Quits the program
        '''
        self.destroy()
        exit()
#----- Step 1: Check if VirtualBox is installed -----#

    def open_virtualbox_link(self, button_clicked):
        webbrowser.open_new(r"https://www.virtualbox.org/wiki/Downloads")

    def check_vbox_installation(self):
        if os.path.isfile(
                'C:\\Program Files\\Oracle\\VirtualBox\\VBoxManage.exe'):
            return True
        else:
            return False

    def first_action_button_clicked(self):
        if self.check_vbox_installation() == True:
            self.action_button.config(
                text="Continue", command=self.second_action_button_clicked)
            self.messagelabel.config(
                text=
                " Click the 'Continue' button to check to see if 64-bit Hardware Virtualization\n"
                +
                " is enabled on your system. If not, you should contact your PC manufacturer\n"
                +
                " for instructions on how to enable 64-bit Hardware Virtualization.\n\n",
                borderwidth=5)
        else:
            self.action_button.config(state=DISABLED)
            messagebox.showerror(
                "Oracle VirtualBox Not Installed",
                "Install Oracle VirtualBox into the default directory" +
                " (Program Files) before continuing. There will be a link to" +
                " download and install Oracle VirtualBox on the next screen.")
            self.messagelabel.config(text="\t\t\tDownload Oracle VirtualBox",
                                     foreground="blue",
                                     cursor="hand2")
            self.messagelabel.bind("<Button-1>", self.open_virtualbox_link)
#----- Step 2: Check if Virtualization is enabled -----#

    def confirm_vtx_enabled(self):
        '''
        Returns: virtualization status
        Object type: string
        About: Provides the status of the VT-X bios setting in the Windows BIOS Menu
        Notes: N/A
        '''
        try:
            input = subprocess.Popen('systeminfo',
                                     shell=False,
                                     stdout=subprocess.PIPE)
        except:
            messagebox.showerror(
                "Error",
                "You may need administrator privelages to run this software. "
                +
                "Try exiting the program and running as an administrator to resolve this issue."
            )
        output = input.stdout.read().decode("utf-8")
        if 'Virtualization Enabled In Firmware: Yes' in output:
            return True
        else:
            messagebox.showerror(
                "Virtualization Check",
                "Virtualization is disabled in Firmware. To resolve this issue, \n"
                +
                "you need to contact your PC manufacturer for instructions on how\n"
                +
                "to enter the BIOS menu and enable Virtualization on your device."
            )
            return False

    def open_vtx_SASNote(self, button_clicked):
        webbrowser.open_new(r"http://support.sas.com/kb/46/250.html")

    def second_action_button_clicked(self):
        self.messagelabel.config(
            text=
            "Checking system for status of 64-bit Hardware Virtualization...")
        if self.confirm_vtx_enabled() == True:
            self.action_button.config(command=self.third_action_button_clicked)
            self.messagelabel.config(
                text=" Virtualization was enabled on your system! \n\n" +
                " Click the 'Continue' button to set up your Shared Folders.\n\n"
            )
        else:
            messagebox.showerror(
                "Virtualization is disabled",
                " Virtualization is disabled on your system." +
                " You will need to contact your PC manufacturer " +
                "(Dell, Acer, Lenovo) for instructions on how to enable 64-bit "
                + " Hardware Virtualization.\n\n")
            self.messagelabel.config(
                text="\t\t\tSAS Note: Virtualization is Disabled",
                fg="blue",
                cursor="hand2")
            self.messagelabel.bind("<Button-1>", self.open_vtx_SASNote)
#----- Step 3: Set up Shared folder (either the default directory or user-selected) -----#

    def openfile(self):
        '''
        Allows the user to search their filesystem for another .OVA file 
        (SAS University Edition vApp) using a gui windows file window.
        '''
        self.ova_filename = filedialog.askopenfilename()
        if self.ova_filename.endswith('.ova'):
            print('SAS University Edition vApp File Location: ' +
                  self.ova_filename)
            self.fifth_action_button_clicked()
        else:
            messagebox.showerror(
                'Wrong Filetype',
                'Please select the SAS University Edition vApp file only.' +
                ' The file should end with the following three-letter extension: ".ova".'
                + '\n\n(Example: unvbasicvapp.ova)')
            self.ova_filename = ''

    def choose_shared_folder(self):
        self.shared_folder = filedialog.askdirectory()
        if os.path.isdir(self.shared_folder):
            if self.shared_folder.endswith('myfolders'):
                self.locate_vapp()
            else:
                messagebox.showerror(
                    'Misspelled Directory',
                    'Please select the "myfolders" folder only.' +
                    ' The folder must be spelled with all lowercase letters and no spaces. '
                    + 'Please try again.')
        else:
            messagebox.showerror(
                'Select a directory',
                'Please try again, and select the "myfolders" folder only.' +
                'The folder must be spelled with all lowercase letters and no spaces. '
            )
            self.shared_folder = r"C:\Users\{}\Documents\SASUniversityEdition\myfolders".format(
                self.user)

    def third_action_button_clicked(self):
        self.messagelabel.config(
            text=
            " Either choose an existing 'myfolders' folder on your hard drive, or a 'myfolders' \n"
            +
            " folder will be created for you, at the following location:\n\n" +
            ' ' + self.shared_folder + '\n\n')
        self.action_button.config(command=self.locate_vapp)
        self.choose_sharedfolder = Button(self,
                                          text="Choose Folder",
                                          command=self.choose_shared_folder)
        self.choose_sharedfolder.grid(row=5, column=2, pady=1)
#----- Step 4: Locate vApp (auto-searches the Downloads folder. If not found, user must search for it) -----#

    def locate_vapp(self):
        self.action_button.config(command=self.fourth_action_button_clicked)
        self.choose_sharedfolder.grid_remove()
        self.messagelabel.config(
            text=
            " Click the 'Continue' button to scan your hard drive for the SAS University Edition \n"
            +
            " vApp. If it is found, you will move on to the next step. If not, click the 'Find vApp'\n"
            +
            " button on the next screen, which will allow you to search for it manually.\n\n"
        )

    def download_UE_ova(self, button_clicked):
        webbrowser.open_new(
            r"https://login.sas.com/opensso/UI/Login?realm=/extweb&goto=https%3A%2F%2Fwww.sas.com%2Fstore%2Fexpresscheckout.ep%3FstoreCode%3DSAS_US%26storeCode%3DSAS_US%26item%3DDPUNVE001_VirtualBox&req=ph&locale="
        )

    def fourth_action_button_clicked(self):
        list_of_files = glob.glob(self.downloads + '\\*.ova')
        if list_of_files != []:
            latest_file = max(list_of_files, key=os.path.getctime)
            self.ova_filename = latest_file
        else:
            messagebox.showinfo(
                "Error",
                "The SAS University Edition vApp was not found in your system's "
                +
                "'Downloads' Folder. \n\nPlease search your system files for the location "
                +
                "of the SAS University Edition vApp by clicking on the 'Find vApp' button on the"
                +
                " next page. \n\nIf you do not yet have the SAS University Edition vApp,"
                +
                " you can download it by clicking on the link on the next screen."
            )
            self.action_button.config(state=DISABLED)
            self.messagelabel.config(
                text="\t\t\tDownload SAS University Edition vApp",
                foreground="blue",
                cursor="hand2")
            self.messagelabel.bind("<Button-1>", self.download_UE_ova)
            self.choose_sharedfolder = Button(self,
                                              text="Find vApp",
                                              command=self.openfile)
            self.choose_sharedfolder.grid(row=5, column=2, pady=1)
        if self.ova_filename != '' and self.ova_filename.endswith('.ova'):
            self.fifth_action_button_clicked()
#----- Step 5: Checks for duplicate VMs in VirtualBox, then checks for multiple 'SAS University Edition'
#              folders in the 'VirtualBox VMs' folder. -----#

    def fifth_action_button_clicked(self):
        self.choose_sharedfolder.grid_remove()
        self.action_button.config(state='normal',
                                  command=self.check_duplicates)
        self.messagelabel.destroy()
        self.messagelabel = Label(
            self,
            text=
            " Click the 'Continue' button to verify that you do not have any duplicate SAS\n"
            + " University Edition VMs imported into Oracle VirtualBox.\n\n",
            borderwidth=5,
            relief="ridge")
        self.messagelabel.grid(row=1,
                               column=0,
                               columnspan=4,
                               rowspan=4,
                               padx=7,
                               sticky=N + W + E + S)

    def run_command(self, command):
        p = subprocess.Popen(command,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT)
        return iter(p.stdout.readline, b'')

    def check_duplicate_vms(self):
        command = '"C:\\Program Files\\Oracle\\VirtualBox\\VBoxManage.exe" list vms'
        for line in self.run_command(command):
            output = line.decode('utf-8').split()
            for word in output:
                if word in self.checklist:
                    messagebox.showerror(
                        'Already imported',
                        'You have already imported SAS University Edition into Oracle VirtualBox.'
                        +
                        ' Please remove all SAS University Edition Virtual Machines from Oracle '
                        +
                        'VirtualBox before proceeding. To remove them, open Oracle VirtualBox and'
                        +
                        ' right-click on the "SAS University Edition - Powered Off"'
                        +
                        ' tab, then hit remove --> Delete All Files. Do this for all existing SAS '
                        + 'University Edition Virtual Machines in VirtualBox.')
                    notimported = False
                    return notimported
        noduplicates = True
        return noduplicates

    def check_vbox_vms_folder(self):
        vboxvmsfolder = 'C:\\Users\\' + os.getlogin() + '\\VirtualBox VMs'
        vboxvms = os.listdir(vboxvmsfolder)

        if vboxvms != []:
            for item in self.checklist:
                if item in vboxvms:
                    messagebox.showerror(
                        'Already imported', 'The virtual machine "' + item +
                        '" was removed from Oracle VirtualBox incorrectly. ' +
                        'Please delete all SAS University Edition folder(s) from the '
                        + 'following location: \n\n' + vboxvmsfolder)
                    return False

        test = True
        return test

    def check_duplicates(self):
        if self.check_duplicate_vms() == True:
            if self.check_vbox_vms_folder() == True:
                self.sixth_action_button_clicked()
#----- Step 6: Write batch file using information collected above & run batch file to import vApp -----#

    def sixth_action_button_clicked(self):
        self.write_batchfile()
        self.action_button.config(text='Import')
        self.action_button.config(command=self.seventh_action_button_clicked)
        self.messagelabel.config(
            text=
            " Click the 'Import' button to import the SAS University Edition vApp\n "
            + "into Oracle VirtualBox. This may take a few moments. \n\n")

    def write_batchfile(self):
        batchfile = open("Install_SAS_University_Edition.bat", 'w')
        batchfile.write(
            r'set PATH=%PATH%;"C:\Program Files\Oracle\VirtualBox"')
        batchfile.write('\n')
        batchfile.write('VBoxManage import ' + self.ova_filename)
        batchfile.write('\n')
        if os.path.isdir(self.shared_folder):
            batchfile.write(
                'VBoxManage sharedfolder add "SAS University Edition" --name myfolders --hostpath '
                + self.shared_folder + ' --automount')
        else:
            batchfile.write('MKDIR ' + self.shared_folder)
            batchfile.write('\n')
            batchfile.write(
                'VBoxManage sharedfolder add "SAS University Edition" --name myfolders --hostpath '
                + self.shared_folder + ' --automount')
        batchfile.close()

    def import_ova_file(self):
        try:
            subprocess.call("Install_SAS_University_Edition.bat")
            messagebox.showinfo(
                "Successfully Installed",
                "SAS University Edition has now been imported into Oracle VirtualBox.\n\n"
                + "A shared folder was created at the following location:\n" +
                self.shared_folder + '\n\n')
            self.successful_import()
        except:
            messagebox.showerror(
                "Error",
                "There was an issue installing SAS University Edition. " +
                "Try running the 'Install_SAS_University_Edition.bat' file " +
                "with administrator privelages.")

    def seventh_action_button_clicked(self):
        self.import_ova_file()


#----- Step 7: Open Oracle VirtualBox and close the installer -----#

    def successful_import(self):
        self.action_button.config(text='Run')
        self.action_button.config(command=self.run_button_clicked)
        self.messagelabel.config(
            text=" You are now finished setting up SAS University Edition. \n"
            +
            " Click the 'Run' button to run Oracle VirtualBox and quit the Installer. \n\n"
        )

    def run_button_clicked(self):
        '''
        Allows users to run Oracle VirtualBox after a successful import and quit the installer.
        '''
        try:
            subprocess.Popen(
                ['C:\\Program Files\\Oracle\\VirtualBox\\VirtualBox.exe'])
            messagebox.showinfo(
                "Successfully Installed",
                "The SAS University Edition Install Tool will quit " +
                "after clicking OK. You can now begin using SAS University Edition in Oracle VirtualBox "
                +
                "by right-clicking 'SAS University Edition' and hitting 'Start'."
            )
            self.quit()
        except:
            messagebox.showerror(
                "Error",
                "You may need administrator privelages to open Oracle VirtualBox. "
                +
                "Try opening Oracle VirtualBox manually by searching for 'Oracle VirtualBox' "
                +
                "in the Windows Search Bar (bottom left hand corner of the screen)."
            )
示例#34
0
    def __init__(self, master, columns, column_weights=None, cnf={}, **kw):
        """
        Construct a new multi-column listbox widget.

        :param master: The widget that should contain the new
            multi-column listbox.

        :param columns: Specifies what columns should be included in
            the new multi-column listbox.  If ``columns`` is an integer,
            the it is the number of columns to include.  If it is
            a list, then its length indicates the number of columns
            to include; and each element of the list will be used as
            a label for the corresponding column.

        :param cnf, kw: Configuration parameters for this widget.
            Use ``label_*`` to configure all labels; and ``listbox_*``
            to configure all listboxes.  E.g.:

                >>> mlb = MultiListbox(master, 5, label_foreground='red')
        """
        # If columns was specified as an int, convert it to a list.
        if isinstance(columns, int):
            columns = list(range(columns))
            include_labels = False
        else:
            include_labels = True

        if len(columns) == 0:
            raise ValueError("Expected at least one column")

        # Instance variables
        self._column_names = tuple(columns)
        self._listboxes = []
        self._labels = []

        # Pick a default value for column_weights, if none was specified.
        if column_weights is None:
            column_weights = [1] * len(columns)
        elif len(column_weights) != len(columns):
            raise ValueError("Expected one column_weight for each column")
        self._column_weights = column_weights

        # Configure our widgets.
        Frame.__init__(self, master, **self.FRAME_CONFIG)
        self.grid_rowconfigure(1, weight=1)
        for i, label in enumerate(self._column_names):
            self.grid_columnconfigure(i, weight=column_weights[i])

            # Create a label for the column
            if include_labels:
                l = Label(self, text=label, **self.LABEL_CONFIG)
                self._labels.append(l)
                l.grid(column=i, row=0, sticky="news", padx=0, pady=0)
                l.column_index = i

            # Create a listbox for the column
            lb = Listbox(self, **self.LISTBOX_CONFIG)
            self._listboxes.append(lb)
            lb.grid(column=i, row=1, sticky="news", padx=0, pady=0)
            lb.column_index = i

            # Clicking or dragging selects:
            lb.bind("<Button-1>", self._select)
            lb.bind("<B1-Motion>", self._select)
            # Scroll whell scrolls:
            lb.bind("<Button-4>", lambda e: self._scroll(-1))
            lb.bind("<Button-5>", lambda e: self._scroll(+1))
            lb.bind("<MouseWheel>", lambda e: self._scroll(e.delta))
            # Button 2 can be used to scan:
            lb.bind("<Button-2>", lambda e: self.scan_mark(e.x, e.y))
            lb.bind("<B2-Motion>", lambda e: self.scan_dragto(e.x, e.y))
            # Dragging outside the window has no effect (diable
            # the default listbox behavior, which scrolls):
            lb.bind("<B1-Leave>", lambda e: "break")
            # Columns can be resized by dragging them:
            l.bind("<Button-1>", self._resize_column)

        # Columns can be resized by dragging them.  (This binding is
        # used if they click on the grid between columns:)
        self.bind("<Button-1>", self._resize_column)

        # Set up key bindings for the widget:
        self.bind("<Up>", lambda e: self.select(delta=-1))
        self.bind("<Down>", lambda e: self.select(delta=1))
        self.bind("<Prior>", lambda e: self.select(delta=-self._pagesize()))
        self.bind("<Next>", lambda e: self.select(delta=self._pagesize()))

        # Configuration customizations
        self.configure(cnf, **kw)
示例#35
0
    root.after(2000, startReadLoop)


def resize_image(event):
    new_width = event.width
    new_height = event.height
    image = currentImage.resize((new_width, new_height))
    photo = ImageTk.PhotoImage(image)
    panel.config(image=photo)
    panel.image = photo  # avoid garbage collection


def resource_path(relative_path):
    if hasattr(sys, '_MEIPASS'):
        return os.path.join(sys._MEIPASS, relative_path)
    return os.path.join(os.path.abspath("."), relative_path)


currentMapImg = getImagePath('ammo')

im = Image.open(currentMapImg)
currentImage = im.copy()
img = ImageTk.PhotoImage(im)
panel = Label(root, image=img, bg="black")
panel.image = img
panel.bind('<Configure>', resize_image)
panel.pack(fill="both", expand="yes")

root.after(1000, startReadLoop)
root.mainloop()
示例#36
0
class MainWin(Tk) :
	def __init__(self,title,*args,**kwargs) :
		Tk.__init__(self,*args,**kwargs);
		self.title(title);
		self.docsLim = "-1";
		self.docs = [];
		self.raw  = [];
		self._addMenu();
		self._addUpperTemplate();
		self._addLowerTemplate();

	def _addMenu(self) :
		mainMenu = Menu(self);
		
		fileMenu = Menu(mainMenu , tearoff=0);
		fileMenu.add_command(label="Mine PDF",command=self._pdfMine);
		fileMenu.add_command(label="Site crawling" + " " * 20,command=self._webMine);
		fileMenu.add_separator();
		fileMenu.add_command(label="Exit",command=lambda : exit(0));

		helpMenu = Menu(mainMenu , tearoff=0);
		helpMenu.add_command(label="About" + " " * 20,command=self._about);
		helpMenu.add_command(label="Manual",command=self._manual);

		mainMenu.add_cascade(label="File",menu=fileMenu);
		mainMenu.add_cascade(label="Help",menu=helpMenu);
		self.config(menu=mainMenu);


	def _addUpperTemplate(self) :
		lblFrame = LabelFrame(self,text=" Documents ")
		lblFrame.grid(row=0,column=0,sticky="new",padx=15,pady=15,columnspan=2);

		frame = Frame(lblFrame);
		Label(frame,text="Limit Documents").grid(row=0,column=0,sticky="w",pady=5,padx=10);
		self.combo = ttk.Combobox(frame,values=["None"] + [i for i in range(1,20)] , state="readonly");
		def chooseLim(event) : self.combo.config(state="disabled");self.docsLim=self.combo.get();print(self.docsLim);
		self.combo.bind("<<ComboboxSelected>>", chooseLim);
		self.combo.grid(row=0,column=1,sticky="w")
		self.combo.current(0)
		frame.grid(row=0,column=0,sticky="w")

		frame = Frame(lblFrame)
		xscrollbar = Scrollbar(frame , orient="horizontal")
		xscrollbar.grid(row=1, column=0, sticky="snew")

		yscrollbar = Scrollbar(frame)
		yscrollbar.grid(row=0, column=1, sticky="snew")

		self.text = Text(frame , height=10 , font=("Consolas",12) , wrap="none" , xscrollcommand=xscrollbar.set , yscrollcommand=yscrollbar.set)
		self.text.grid(row=0,column=0,sticky="snew")

		xscrollbar.config(command=self.text.xview)
		yscrollbar.config(command=self.text.yview)		
		frame.grid(row=1,column=0,sticky="snew",padx=10,pady=(5,0))
	
		self.fileChoose = Label(lblFrame,text="Import from a text file",font=("consolas",10),fg="blue",cursor="hand2");
		self.fileChoose.grid(row=2,column=0,sticky="w",padx=10)
		self.fileChoose.bind("<Button-1>",lambda event : self._importText());

		rightFrame = Frame(lblFrame);
		Button(rightFrame,text="Add as a Document",relief="groove",command=self._addDoc).grid(row=0,column=0,ipady=4,padx=(5,15),pady=2,sticky="we")
		Button(rightFrame,text="Remove all Documents",relief="groove",command=self._removeDocs).grid(row=1,column=0,ipady=4,padx=(5,15),pady=2,sticky="we")
		Button(rightFrame,text="Past a Document",relief="groove",command=self._pastDoc).grid(row=2,column=0,ipady=4,padx=(5,15),pady=2,sticky="we")
		Button(rightFrame,text="Show Documents",relief="groove",command=self._showDocs).grid(row=3,column=0,ipady=4,padx=(5,15),pady=2,sticky="we");

		rightFrame.grid(row=1,column=1)

		frame2 = Frame(lblFrame);
		Label(frame2,text="Search Engine Mode").grid(row=0,column=0,sticky="w",pady=5,padx=10);
		self.combo2 = ttk.Combobox(frame2,values=["Boolean Retrival Model","Inverted Index Model","Vector Space Model"] , state="readonly");
		self.combo2.grid(row=0,column=1,sticky="we",columnspan=2,padx=(10,10))
		self.combo2.current(0)
		frame2.grid(row=3,column=0,sticky="snew",pady=15);
		frame2.columnconfigure(2,weight=1)

		frame.columnconfigure(0,weight=1);
		self.columnconfigure(0,weight=1);
		self.rowconfigure(0,weight=1);
		frame.rowconfigure(0,weight=1);
		lblFrame.rowconfigure(0,weight=4);
		lblFrame.columnconfigure(0,weight=1);

	def _addLowerTemplate(self) :
		self.searchEntry = Entry(self , font=("consolas",12));
		self.searchEntry.grid(row=1,column=0,ipady=2,padx=15,pady=10,sticky="wen")
		Button(self,text="Search",relief="groove",command=self._search).grid(row=1,column=1,ipadx=15,ipady=1,padx=(0,15),pady=(10,30));

	def _addDoc(self) :
		if self.docsLim == "-1" :
			msg.showerror("Error","You should set the limited number of documents first");
			return;
		else :
			if self.docsLim == "None" : 
				doc = self.text.get("0.1" , "end")
				raw = doc;
				doc = doc.replace("\n"," ");
				doc = normalizeWord(doc);       #
				if len(doc) == 0 : print("empty");return;
				self.docs.append(doc);
				self.raw.append(raw);
				print(self.docs)
			else : #must be then from 1 to 19
				if int(self.docsLim) == len(self.docs) : msg.showerror("Error","Maximum number of documents reached"); 
				else : 
					doc = self.text.get("0.1" , "end")
					raw = doc;
					doc = doc.replace("\n"," ");
					doc = normalizeWord(doc);
					#self.docs.append(filterFromSW(doc));
					if len(doc) == 0 : print("empty");return;
					self.docs.append(doc);
					self.raw.append(raw);
					print(self.docs)
				
	def _removeDocs(self) :
		self.docs = [];
		self.raw  = [];
		self.docsLim = "-1";
		self.combo.configure(state="readonly");
		self.combo.current(0);

	def _pastDoc(self) :
		from clipboard import paste
		content = paste();
		if not content.replace(" ","").replace("\n","") == "" : 
			self.text.delete("0.1","end");
			self.text.insert("0.1" , content)

	def _showDocs(self) :
		out = "";
		if len(self.docs) == 0 : out = "No documents added so far";
		else :
			for i in range(len(self.raw)) :
				out += "-Doc <" + str(i+1) + "> :\n" + self.raw[i] + "\n\n"; 
		self.popup("jesus christ" , out);

	def _pdfMine(self) :
		def isPdfFile(filePath) :
			if filePath.split(".")[-1] == "pdf" : return True;
			return False;
		pdfFilePath = askopenfile();
		try :
			if isPdfFile(pdfFilePath.name) :
		
				content = minePdf(pdfFilePath.name);
				if content != False :
					self.text.delete("0.1","end");
					self.text.insert("0.1",content);
		except : print("passed");

	def _webMine(self) :
		def getURL(entry=Entry()) :
			given = entry.get();
			if given.replace(" ","") == "" : return;
			content = mineSite(given);
			if content == False : msg.showerror("Error","Invalid URL specified or No Internet connection Found");
			else :
				self.text.delete("0.1","end");
				self.text.insert("0.1",content);
				
		pop = Tk();
		pop.title("jesus christ")
		pop.columnconfigure(0,weight=1);
		Label(pop,text="please fill below a valid url").grid(row=0,column=0,sticky="w",padx=10,pady=5)
		entry = Entry(pop,font=("Consolas",11));
		entry.grid(row=1,column=0,sticky="we",padx=10,pady=(5,20),ipadx=2,ipady=2);
		Button(pop,text="retrieve",relief="groove",command=lambda : getURL(entry)).grid(row=1,column=1,padx=5,pady=(5,20),ipadx=3,ipady=1);
		pop.minsize(400,100)
		pop.maxsize(800,100)
		pop.mainloop();

	def _manual(self) :
		content = "";
		try :
			with open("README.txt","r") as file :
				content = "".join(file.readlines());
		except : pass;
		finally :
			self.popup("jesus christ" , content);

	def _about(self) :
		pop = Tk();
		pop.title("jesus christ")
		pop.resizable(False , False)
		Label(pop,text="Team IR project 1st term 2018 - 2019\n\n").grid(row=0,column=0,padx=(10,20),pady=(10,100))
		pop.mainloop();

	def _importText(self) :
		def isTextFile(filePath) :
			if filePath.split(".")[-1] == "txt" : return True;
			return False;
		try :
			with askopenfile() as file :
				if isTextFile(file.name) : 
					content = "";
					for line in file.readlines() :
						if not line.replace(" ","").replace("\n","") == "" :
							content += line;
					if not content == "" :  
						self.text.delete("0.1","end");
						self.text.insert("0.1",content);
		except : return;

	def _search(self) :
		if self.docsLim != "-1" and len(self.docs) != 0 :
			mode  = self.combo2.get();
			query = self.searchEntry.get();
			if query.replace(" ","") == "" : return; 
			if mode == "Boolean Retrival Model" :
				model1 = BooleanModel(self.docs , self.raw , normalizeWord(query , True));
				result = model1.getSol()
				if result == False : msg.showerror("Error","Syntax error found in the query");
				else :
					#print(result);
					self.popup("jesus christ" , model1.foramtter(result))

			elif mode == "Inverted Index Model" : 
				model2 = InvertedIndex(self.docs , self.raw , normalizeWord(query));
				result = model2.getSol();
				self.popup("jesus christ" , model2.formatter(result));
				
			elif mode == "Vector Space Model" :
				model3 = VectorSpaceModel(self.docs , self.raw , normalizeWord(query));
				result = model3.getSol();
				self.popup("jesus christ" , model3.formatter(result));

		else :
			msg.showerror("Error","Please add documents first");

	@staticmethod
	def popup(title , content) :
		root = Tk();
		root.title(title)
		frame = Frame(root)
		xscrollbar = Scrollbar(frame , orient="horizontal")
		xscrollbar.grid(row=1, column=0, sticky="snew")

		yscrollbar = Scrollbar(frame)
		yscrollbar.grid(row=0, column=1, sticky="snew")

		text = Text(frame , height=10 , font=("Consolas",12) , wrap="none" , xscrollcommand=xscrollbar.set , yscrollcommand=yscrollbar.set)
		text.grid(row=0,column=0,sticky="snew")

		xscrollbar.config(command=text.xview)
		yscrollbar.config(command=text.yview)		
		frame.grid(row=0,column=0,sticky="snew",padx=10,pady=(5,0))

		text.insert("0.1" , content);
		text.configure(state="disabled");

		root.columnconfigure(0,weight=1);
		root.rowconfigure(0,weight=1);
		frame.columnconfigure(0,weight=1);
		frame.rowconfigure(0,weight=1);


	def run(self) :
		self.mainloop();
示例#37
0
	def __init__(self, controller, width, height, *args, **kwargs):
		BaseWindow.__init__(self, controller, *args, **kwargs)
		self.controller = controller
		self.controller.configure_toplevel(self)
		self.resizable(True, True)
		self.attributes('-topmost', False) #Remove the toplevel priority
		self.set_exit_function(self.exit)
		self.set_title("Canvas")
		self.file = None
		self.width = int(width)
		self.height = int(height)
		self.geometry(f"{WIDTH}x{HEIGHT}")
		self.bind("<Escape>", self.exit)
		self.top_bar.pack(side = "top", fill = "x", pady = (2,0))
		self.magnifying_glass_image = load_tk_image_from_bytes_array(magnifying_glass_bytes)
		self.floppy_image = load_tk_image_from_bytes_array(floppy_bytes)
		self.bytes_image=  load_tk_image_from_bytes_array(export_to_bytes_bytes)
		self.horizontal_flip_image =  load_tk_image_from_bytes_array(flip_horizontal_bytes)
		self.vertical_flip_image = load_tk_image_from_bytes_array(flip_vertical_bytes)
		self.rotate_left_image = load_tk_image_from_bytes_array(rotate_left_bytes)
		self.rotate_right_image = load_tk_image_from_bytes_array(rotate_right_bytes)
		self.to_grayscale_image = load_tk_image_from_bytes_array(to_grayscale_bytes)
		self.selection_options_image = load_tk_image_from_bytes_array(selection_options_bytes)
		self.layers_symbol_image = load_tk_image_from_bytes_array(layers_symbol_bytes)
		self.folder_options_symbol = load_tk_image_from_bytes_array(folder_options_symbol_bytes)
		self.effects_wand_symbol = load_tk_image_from_bytes_array(effects_wand_symbol_bytes)
		self.copy_options_symbol = load_tk_image_from_bytes_array(copy_options_symbol_bytes)
		self.undo_symbol = load_tk_image_from_bytes_array(undo_symbol_bytes)
		self.redo_symbol = load_tk_image_from_bytes_array(redo_symbol_bytes)

		self.drawtips_references = []
		self.project = PixelProject(self.width, self.height)

		panes = PanedWindow(self, orient = "horizontal", sashpad=3, sashrelief ="sunken")
		panes.pack(fill = "both", expand = True)
		panes.config(borderwidth = 0)

		self.left_side_frame = Frame(panes)
		self.left_side_frame.pack(fill = "both", expand = False, side = "left")
		panes.add(self.left_side_frame)

		tool_buttons = []
		self.gif_tool_bar = ToolBar(tool_buttons, self.left_side_frame)
		self.gif_tool_bar.pack(side = "top", fill = "x", pady = (0,2))

		save_options_button = Label(self.gif_tool_bar, image = self.floppy_image, font = "bold")
		save_options_button.pack(side = "left")
		save_menu = Menu(self, tearoff=0)
		save_menu.add_command(label="Export Gif", command=self.export_gif)
		save_menu.add_command(label="Export Selected Frame", command=self.export_selected_layer)
		save_menu.add_command(label="Export Selected Layer", command=self.export_selected_frame)
		# gif_menu.add_command(label="Export Project as Zip", command=self.export_zip)
		# gif_menu.add_command(label="Export Project as .lpixel", command=self.flip_selection_horizontal)
		# gif_menu.add_command(label="Load Folder as Layers in Current Frame", command=self.load_folder_as_layers)
		bind_popup("<Button-1>", save_options_button, save_menu)

		load_options_button = Label(self.gif_tool_bar, image = self.folder_options_symbol, font = "bold")
		load_options_button.pack(side = "left")
		load_options_menu = Menu(self, tearoff=0)
		load_options_menu.add_command(label="Import Gif as Frames", command=self.import_gif)
		load_options_menu.add_command(label="Load Folder as Frames", command=self.load_folder_as_frames)
		load_options_menu.add_command(label="Load Folder as Layers in Selected Frame", command=self.load_folder_as_layers)
		bind_popup("<Button-1>", load_options_button, load_options_menu)

		preview_options_button = Label(self.gif_tool_bar, image = self.magnifying_glass_image, font = "bold")
		preview_options_button.pack(side = "left")
		preview_options_menu = Menu(self, tearoff=0)
		preview_options_menu.add_command(label="Inspect Selected Frame", command=self.inspect_frame)
		preview_options_menu.add_command(label="Inspect Selected Layer", command=self.inspect_layer)
		bind_popup("<Button-1>", preview_options_button, preview_options_menu)

		panes2 = PanedWindow(self.left_side_frame, orient = "vertical", sashpad=3, sashrelief ="sunken")
		panes2.pack(fill = "both", expand = True, padx = 4, pady = (0,4))
		panes2.config(borderwidth = 0)

		self.gif_view = LayerViewer(self.project, self.width, self.height, panes2)
		self.gif_view.pack(fill = "both", expand = True)
		panes2.add(self.gif_view)
		
		self.frame_manager = LayerManager(self, self.project, panes2)
		self.frame_manager.pack(side = "left", fill = "both", expand = True, pady = 0)
		panes2.add(self.frame_manager)

		self.right_side_frame = Frame(panes)
		self.right_side_frame.pack(fill = "both", expand = True, side = "right")
		panes.add(self.right_side_frame)

		tool_buttons = [
			(self.vertical_flip_image, self.flip_vertical),
			(self.horizontal_flip_image, self.flip_horizontal),
			(self.rotate_left_image, self.rotate_left),
			(self.rotate_right_image, self.rotate_right),
		]
		self.tool_bar = ToolBar(tool_buttons, self.right_side_frame)
		self.tool_bar.pack(side = "top", fill = "x")


		layer_menu = Menu(self, tearoff = 0)
		layer_menu.add_command(label = "Rename Current Layer", command = self.rename_selected_layer)
		layer_menu.add_command(label = "Export Current Layer", command = self.save)
		layer_menu.add_command(label = "Export Current Layer as Bytes (Console)", command = self.export_selected_layer_as_bytes)
		layer_menu.add_command(label = "Delete Current Layer", command = self.delete_selected_layer)
		layer_menu.add_command(label = "Duplicate Current Layer", command = self.copy_selected_layer)
		layer_menu.add_command(label = "Promote Current Layer", command = self.promote_selected_layer)
		layer_menu.add_command(label = "Demote Current Layer", command = self.demote_selected_layer)
		layer_menu.add_command(label = "Merge Layer Down", command = self.merge_selected_layer_down)
		layer_menu.add_separator()
		layer_menu.add_command(label = "Rename Current Frame", command = self.rename_selected_frame)
		layer_menu.add_command(label = "Export Current Frame", command = self.save_selected_frame)
		layer_menu.add_command(label = "Export Current Frame as Bytes (Console)", command = self.export_selected_frame_as_bytes)
		layer_menu.add_command(label = "Delete Current Frame", command = self.delete_selected_frame)
		layer_menu.add_command(label = "Duplicate Current Frame", command = self.copy_selected_frame)
		layer_menu.add_command(label = "Promote Current Frame", command = self.promote_selected_frame)
		layer_menu.add_command(label = "Demote Current Frame", command = self.demote_selected_frame)
		layer_menu.add_command(label = "New Layer in Current Frame", command = self.new_layer_in_selected_frame)
		layer_menu.add_command(label = "New Layer from Image in Current Frame", command = self.new_layer_from_image_in_selected_frame)
		self.layer_options_menu_button = Label(self.tool_bar, image = self.layers_symbol_image, font = "bold")
		self.layer_options_menu_button.pack(side = "left")
		bind_popup("<Button-1>", self.layer_options_menu_button, layer_menu)

		selection_menu = Menu(self, tearoff=0)
		selection_menu.add_command(label = "Flood Fill Selection", command = self.fill_selection)
		selection_menu.add_command(label = "Flip Selection Vertical", command = self.flip_selection_vertical)
		selection_menu.add_command(label = "Flip Selection Horizontal", command = self.flip_selection_horizontal)
		selection_menu.add_command(label = "Rotate Selection Right", command = self.rotate_selection_right)
		selection_menu.add_command(label = "Rotate Selection Left", command = self.rotate_seletion_left)
		selection_menu.add_command(label = "Export Selection", command = self.export_selection)
		selection_menu.add_command(label = "Export Selection as Bytes (Console)", command = self.export_selection_as_bytes)
		selection_menu.add_separator()
		selection_menu.add_command(label = "Copy Selection to Clipboard", command = self.copy_selection_to_clipboard)
		selection_menu.add_command(label = "New Layer from Selection", command = self.new_layer_image_from_selection)
		selection_menu.add_separator()
		selection_menu.add_command(label = "Apply Blur Filter to Selection", command = self.effect_blur_selection)
		selection_menu.add_command(label = "Apply Contour Filter to Selection", command = self.effect_contour_selection)
		selection_menu.add_command(label = "Apply Detail Filter to Selection", command = self.effect_detail_selection)
		selection_menu.add_command(label = "Apply Edge Enhance Filter to Selection", command = self.effect_edge_enhance_selection)
		selection_menu.add_command(label = "Apply Edge Enhance More Filter to Selection", command = self.effect_edge_enhance_more_selection)
		selection_menu.add_command(label = "Apply Emboss Filter to Selection", command = self.effect_emboss_selection)
		selection_menu.add_command(label = "Apply Find Edges Filter to Selection", command = self.effect_find_edges_selection)
		selection_menu.add_command(label = "Apply Sharpen Filter to Selection", command = self.effect_sharpen_selection)
		selection_menu.add_command(label = "Apply Smooth Filter to Selection", command = self.effect_smooth_selection)
		selection_menu.add_command(label = "Apply Smooth More Filter to Selection", command = self.effect_smooth_more_selection)
		selection_menu.add_command(label = "Apply Gaussian Filter to Selection", command = self.effect_gaussian_selection)
		selection_menu.add_command(label = "Apply Box Blur Filter to Selection", command = self.effect_box_blur_selection)
		selection_menu.add_command(label = "Apply Median Filter to Selection", command = self.effect_median_filter_selection)
		selection_menu.add_command(label = "Apply Min Filter to Selection", command = self.effect_min_filter_selection)
		selection_menu.add_command(label = "Apply Max Filter to Selection", command = self.effect_max_filter_selection)
		selection_menu.add_command(label = "Apply Mode Filter to Selection", command = self.effect_mode_filter_selection)
		self.selections_options_menu_button = Label(self.tool_bar, image = self.selection_options_image, font = "bold")
		self.selections_options_menu_button.pack(side = "left")
		bind_popup("<Button-1>", self.selections_options_menu_button, selection_menu)

		effects_menu = Menu(self, tearoff=0)
		effects_menu.add_command(label = "Apply Blur Filter", command = self.effect_blur_layer)
		effects_menu.add_command(label = "Apply Contour Filter", command = self.effect_contour_layer)
		effects_menu.add_command(label = "Apply Detail Filter", command = self.effect_detail_layer)
		effects_menu.add_command(label = "Apply Edge Enhance Filter", command = self.effect_edge_enhance_layer)
		effects_menu.add_command(label = "Apply Edge Enhance More Filter", command = self.effect_edge_enhance_more_layer)
		effects_menu.add_command(label = "Apply Emboss Filter", command = self.effect_emboss_layer)
		effects_menu.add_command(label = "Apply Find Edges Filter", command = self.effect_find_edges_layer)
		effects_menu.add_command(label = "Apply Sharpen Filter", command = self.effect_sharpen_layer)
		effects_menu.add_command(label = "Apply Smooth Filter", command = self.effect_smooth_layer)
		effects_menu.add_command(label = "Apply Smooth More Filter", command = self.effect_smooth_more_layer)
		effects_menu.add_command(label = "Apply Gaussian Filter", command = self.effect_gaussian_layer)
		effects_menu.add_command(label = "Apply Box Blur Filter", command = self.effect_box_blur_layer)
		effects_menu.add_command(label = "Apply Median Filter", command = self.effect_median_filter_layer)
		effects_menu.add_command(label = "Apply Min Filter", command = self.effect_min_filter_layer)
		effects_menu.add_command(label = "Apply Max Filter", command = self.effect_max_filter_layer)
		effects_menu.add_command(label = "Apply Mode Filter", command = self.effect_mode_filter_layer)
		self.effects_options_menu_button = Label(self.tool_bar, image = self.effects_wand_symbol, font = "bold")
		self.effects_options_menu_button.pack(side = "left")
		bind_popup("<Button-1>", self.effects_options_menu_button, effects_menu)

		copy_options_menu = Menu(self, tearoff=0)
		copy_options_menu.add_command(label = "Copy Current Layer to Clipboard", command = self.copy_selected_layer_to_clipboard)
		copy_options_menu.add_command(label = "Copy Current Frame to Clipboard", command = self.copy_selected_frame_to_clipboard)
		copy_options_menu.add_command(label = "Copy Selection to Clipboard", command = self.copy_selection_to_clipboard)
		copy_options_menu.add_separator()
		copy_options_menu.add_command(label = "Paste As New Layer in Current Frame", command = self.paste_as_new_layer_in_current_frame)
		copy_options_menu.add_command(label = "Paste As New Layer in New Frame", command = self.paste_as_new_layer_in_new_frame)
		copy_options_button = Label(self.tool_bar, image = self.copy_options_symbol, font = "bold")
		copy_options_button.pack(side = "left")
		bind_popup("<Button-1>", copy_options_button, copy_options_menu)

		undo_button =  Label(self.tool_bar, image = self.undo_symbol)
		undo_button.pack(side = "left")
		undo_button.bind("<Button-1>", self.undo)

		redo_button =  Label(self.tool_bar, image = self.redo_symbol)
		redo_button.pack(side = "left")
		redo_button.bind("<Button-1>", self.redo)

		self.canvas_frame = ttk.LabelFrame(self.right_side_frame, text = "")
		self.canvas_frame.pack(fill = "both", expand = True, anchor = "n", padx = 3)
		inner_frame = Frame(self.canvas_frame)
		inner_frame.pack(fill = "both", expand = True, side = "top", anchor = "n", padx = 4, pady = 4)
		self.canvas = LyfeCanvas(self.project, inner_frame)
		force_aspect(self.canvas, inner_frame, float(self.width)/float(self.height))

		self.footer = Frame(self.right_side_frame)
		self.footer.pack(side = "bottom", fill = "x", expand = False, padx = 3)
		self.footer_var = StringVar()
		self.footer_label = Label(self.footer, textvariable = self.footer_var)
		self.footer_label.pack(side = "left", expand = False, fill = "x")

		self.grip = ttk.Sizegrip(self)
		self.grip.place(relx=1.0, rely=1.0, anchor="se")
		self.grip.bind("<ButtonPress-1>", self.on_press)
		self.grip.bind("<B1-Motion>", self.on_resize)
		self.grip.bind("<ButtonRelease-1>", self.on_release)

		self.canvas.bind_middle(self.eyedrop)
		self.canvas.bind_movement(self.on_mouse_move)
		self.canvas.canvas.bind("<ButtonPress-1>", self.on_canvas_click)
		self.canvas.canvas.bind("<B1-Motion>", self.on_canvas_drag)
		self.canvas.canvas.bind("<ButtonRelease-1>", self.on_canvas_release)
		self.canvas.canvas.bind("<ButtonPress-3>", self.on_erase_start)
		self.canvas.bind_right_drag(self.on_erase)
		self.canvas.canvas.bind("<ButtonRelease-3>", self.on_erase_end)

		self.canvas.after_idle(self.refresh)
示例#38
0
class WordGui(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)

        #self.words = ['chien', 'chat', 'lapin', 'couloir', "l'oeuf"]
        self.word_dict = {}
        self.word_dict_out = {}
        self.prev_image = None  # previously select image / widget
        self.prev_audio = None  # previously selected audio / widget
        self.selected_image = None
        self.selected_audio = None
        self.parent = parent
        self.ROWS = 5
        self.COLS = 6
        self.title = None
        self.save_lbl = Label()
        self.image_dict = {}
        self.queue = queue.Queue()
        self.file_opt = options = {}

        self.initUI()

    def process_queue(self):
        try:
            msg = self.queue.get(0)
            # Show result of the task if needed
        except queue.Empty:
            self.after(100, self.process_queue)

    def do_image(self, event):
        if self.prev_image:
            self.prev_image.configure(state=NORMAL)
        self.prev_image = event.widget
        event.widget.configure(state=ACTIVE)
        self.selected_image = event.widget.cget('image')

    def askopenfilename(self):
        """Returns an opened file in read mode.
        This time the dialog just returns a filename and the file is opened by your own code.
        """
        # get filename
        filename = filedialog.askopenfilename(**self.file_opt)
        # open file on your own
        if filename:
            with open(str(filename), 'r') as csvfile:
                reader = csv.DictReader(csvfile)

                for row in list(reader):
                    self.word_dict[row['word']] = {}
                    self.word_dict_out[row['word']] = {}

                    for i in row:
                        if str(i) is not 'word':
                            self.word_dict[row['word']].update({i: row[i]})
                            self.word_dict_out[row['word']].update({i: row[i]})

        self.next_word()

    def do_sound(self, event):
        if self.prev_audio:
            self.prev_audio.configure(state=NORMAL)
        self.prev_audio = event.widget
        event.widget.configure(state=ACTIVE)
        self.selected_audio = event.widget.cget("text")

        file_path, file_name = self.w.download(
            self.audio_links[self.selected_audio])

        self.downloaded_audio = file_name
        self.after(1, self.w.play(file_path))

    def do_skip(self, event):
        if len(self.word_dict) > 0:
            self.selected_audio = None
            self.selected_image = None
            self.next_word()
        else:
            rewrite_word_list(self.word_dict_out)
            print("Should close")

    def do_save(self,
                event):  # This is crazy messy. Focus here for improvement.
        self.save_lbl.config(text="WAIT...")
        if self.selected_image:
            i = self.image_dict[self.selected_image]
            f_name = str(self.current_word) + '.jpg'
            img_filename = "imgs/" + f_name
            i.save(img_filename)
            self.word_dict_out[self.current_word].update(
                {'picture': '<img src="%s" />' % f_name})
        else:
            self.word_dict_out[self.current_word].update({'picture': "NaN"})

        if self.selected_audio:
            self.word_dict_out[self.current_word].update(
                {'pronunciation': "[sound:%s]" % self.downloaded_audio})
        else:
            self.word_dict_out[self.current_word].update(
                {'pronunciation': "NaN"})

        if self.ipa:  # loop these
            if 'ipa' in self.ipa.keys():
                self.word_dict_out[self.current_word].update(
                    {'ipa': str(self.ipa['ipa'])})
            else:
                self.word_dict_out[self.current_word].update({'ipa': "NaN"})

            if 'gender' in self.ipa.keys():
                self.word_dict_out[self.current_word].update(
                    {'gender': str(self.ipa['gender'])})
            else:
                self.word_dict_out[self.current_word].update({'gender': "NaN"})
        else:
            self.word_dict_out[self.current_word].update({'ipa': "NaN"})
            self.word_dict_out[self.current_word].update({'gender': "NaN"})

        if len(self.word_dict) > 0:
            self.next_word()
        else:
            rewrite_word_list(self.word_dict_out)
            print("Should close")

    def new_window(self):
        self.newWindow = Toplevel(self.master)
        self.app = PreferencesDialog(self.newWindow)

    def next_word(self):

        self.current_word = self.word_dict.popitem()[0]

        for label in self.grid_slaves():
            label.grid_forget()

        lang, output, forvo_api_key, pons_api_key, pons_lang, pn_dict, microsoft_api_key = read_config(
        )
        self.w = Word(self.current_word, lang, pn_dict, pons_api_key,
                      forvo_api_key, output, microsoft_api_key)
        self.audio_links = self.w.get_audio_links()
        self.ipa = self.w.get_ipa()
        self.images = self.w.get_images()

        self.title = Label(self,
                           text=self.current_word,
                           font=("Helvetica", 25),
                           height=2)
        self.title.grid(row=0, columnspan=4, sticky=W + E)

        # We put the SKIP and SAVE buttons up here in case the audio/images fails
        self.skip_lbl = Label(self,
                              text="SKIP",
                              font=("Helvetica", 25),
                              height=2)
        self.skip_lbl.bind("<Button-1>", self.do_skip)
        self.skip_lbl.grid(row=0, column=4, padx=3, sticky=W + E)

        self.save_lbl = Label(self,
                              text="SAVE",
                              font=("Helvetica", 25),
                              height=2)
        self.save_lbl.bind("<Button-1>", self.do_save)
        self.save_lbl.grid(row=0, column=5, padx=3, pady=3, sticky=W + E)

        for num in range(0, self.COLS):
            if self.audio_links:
                if num < len(self.audio_links):

                    audio_links = list(self.audio_links.items())
                    snd = Label(self,
                                text=str(audio_links[num][0]),
                                font=("Helvetica", 16),
                                height=2)
                    snd.bind("<Button-1>", self.do_sound)
                    snd.grid(row=1, column=num, padx=3, pady=3, sticky=W + E)

        for x in range(2, self.ROWS):
            for y in range(0, self.COLS):
                if self.images:
                    bing_image_obj = self.images.pop()
                    ThreadedTask(self, self.queue, bing_image_obj, x,
                                 y).start()
                    #self.after(100, self.process_queue)

        self.pack()

    def initUI(self):
        self.parent.title("Calculator")

        for col in range(self.COLS):
            self.columnconfigure(col, pad=3, minsize=170)

        for row in range(self.ROWS):
            self.rowconfigure(row, pad=3)

        if len(self.word_dict) > 0:
            self.next_word()
示例#39
0
class Play():

    def StartGame(self,minesAmount,height,width):
        blockWidth=50
        blockHeight=50
        self.minesAmount=minesAmount
        '''function called when we press play'''
        self.gameEngine=GE(minesAmount,height,width)
        self.playWindow=Tk()
        self.playWindow.geometry(str(blockWidth*width+blockWidth//2)+'x'+str(blockHeight*height+blockHeight//2)+'+200+200')
        self.playWindow.title("Minesweeper")
        self.playFrame=PF(self.playWindow,height,width,blockHeight,blockWidth)
        self.playFrame.canvas.bind("<Button-1>", self.leftClick)
        self.playFrame.canvas.bind("<Button-3>", self.rightClick)
        self.playFrame.pack()
        
        self.alive=True
        self.update()

    def leftClick(self,event):
        if self.alive:
            x=event.x//50
            y=event.y//50
            self.alive=self.gameEngine.ExposeBlock(x,y)
            self.update()
        else:
            self.DeadFrame()
            

    def rightClick(self,event):
        if self.alive:
            x=event.x//50
            y=event.y//50
            self.gameEngine.ManageFlags(x,y)
            self.update()
            
    def update(self):
            shownField,activeMines=self.gameEngine.GetStatus()
            self.playFrame.Paint(activeMines,shownField)
            self.checkWin(shownField)

    def checkWin(self,shownField):
        if self.alive:
            currentBlocks=sum([1 for x in shownField if x=='X' or x=='F'])
            if currentBlocks==self.minesAmount:
                self.WinFrame()

    def DeadFrame(self):
        self.playFrame.destroy()
        self.deadScreen=Frame(self.playWindow,bg="red")
        self.deadScreen.pack(fill="both", expand=1)
        self.deadText=Label(self.deadScreen,text="You stepped on a mine!\nClick here to try again.",fg="black",bg="red")
        self.deadText.bind("<Button-1>",self.onClickRestart)
        self.deadText.pack()

    def WinFrame(self):
        self.playFrame.destroy()
        self.winScreen=Frame(self.playWindow,bg="blue")
        self.winScreen.pack(fill="both", expand=1)
        self.winText=Label(self.winScreen,text="You won!\nClick here to try again.",fg="yellow",bg="blue")
        self.winText.bind("<Button-1>",self.onClickRestart)
        self.winText.pack()


        
    def onClickRestart(self,event):
        self.playWindow.destroy()
        main=MainMenu()
        main.main()
class Main():
    """ gets urls from kuvaton.com/1/rand, those urls are not images but links 
    to pages containing those images. After this we get the real images from those urls.
    We then show the user a different image everytime she/he presses a key (any key/mouse button) """
    def __init__(self):
        self.root = Tk()
        self.url = "http://www.kuvaton.com/1/rand/"
        self.root.attributes("-zoomed", True)
        self.root.configure(bg="black")
        self.image_panel = Label(self.root, text="Press Any Key", bg="black")
        self.image_panel.bind("<Key>", self.show_image)
        self.image_panel.bind("<Button>", self.show_image)
        self.image_panel.pack()
        self.image_panel.focus_force()
        self.next_queue = CustList(self)

        self.root.mainloop()

    def give_me_links(self, url):
        url_to_open, pattern = urlopen(
            url
        ), "http://[a-zA-Z0-9\.\/]*\.jpg"  # Try this [.] insted of this[a-zA-Z0-9\.\/]
        print("got links from {}".format(url))
        return re.findall(pattern, BeautifulSoup(url_to_open, "lxml").decode())

    def show_image(self, event=None):

        self.image_panel.configure(height=self.root.winfo_height())
        self.image_panel.unbind("<Key>")

        def set_current_image():
            ready_image = ImageTk.PhotoImage(
                give_resized_image(
                    Image.open(BytesIO(urlopen(self.next_image).read()))))
            self.image_panel.configure(image=ready_image)
            self.image_panel.image = ready_image

        def set_next_image(event=None):
            for i in threading.enumerate():
                print(i)
            kuva_urlit = self.give_me_links(self.next_queue.pop(self))

            for url in kuva_urlit:
                if "kuvei" in url:
                    kuva = url
                    break

            print("got pic link", kuva)
            self.image_panel.bind("<Key>", self.show_image)
            self.next_image = kuva

        def give_resized_image(img):
            window_height = self.root.winfo_height()
            if img.size[0] > window_height:
                width = (float(img.size[0]) * float(
                    (window_height / float(img.size[1]))))
                return img.resize((int(width), window_height),
                                  PIL.Image.ANTIALIAS)
            else:
                return img

        try:
            set_current_image()
        except AttributeError:
            set_next_image()
            set_current_image()

        self.thread = Thread(target=set_next_image)
        self.thread.start()
示例#41
0
class mainGUI(Frame, bootloader, GuiController):
    """ Contains the main view for the application """

    def __init__(self):
        """ Create the initial application GUI environment (tool bars, and other static elements) """
        Frame.__init__(self, self.root)
        self.thread_entry_field = ''  # Hold both search string, and drives autoRefresh logic

        self.menuBar = Menu()
        self.fileMenu = Menu(self.menuBar, tearoff=0)
        self.menuBar.add_cascade(label="File", menu=self.fileMenu, underline=1)
        self.fileMenu.add_command(label="Quit", command=self.root.destroy, underline=1)

        self.optionsMenu = Menu(self.menuBar, tearoff=0)
        self.menuBar.add_cascade(label="Options", menu=self.optionsMenu)
        self.optionsMenu.add_command(label="Settings", command=self.editSettings, underline=1)
        self.helpMenu = Menu(self.menuBar, tearoff=0)
        self.menuBar.add_cascade(label="Help", menu=self.helpMenu)
        self.helpMenu.add_command(label="Help", command=self.program_help, underline=1)
        self.helpMenu.add_command(label="About", command=self.program_about, underline=1)
        self.master.config(menu=self.menuBar)

        self.topFrame = Frame()
        self.thread_entry_box = Entry(self.topFrame)
        self.thread_entry_box.insert(0, self.DEFAULT_THREAD_TEXT)
        self.thread_entry_box.bind('<Return>', lambda event: self.add_thread_GUI())
        # Bind needs to send the event to the handler
        self.thread_entry_box.pack(side='left', fill='x', expand='True', padx=5)

        self.add_thread_btn = Button(self.topFrame)
        self.add_thread_btn['text'] = 'Add New Thread'
        self.add_thread_btn['command'] = lambda: self.add_thread_GUI()
        self.add_thread_btn.pack(side='left', padx=0)

        self.topFrame.pack(fill='x')

        self.create_thread_frame()

    def create_thread_frame(self):
        """ Sets up the main thread frame (where the magic happens) """

        # Sets up frame
        self.thread_list_canvas = Canvas(self.root, borderwidth=0)
        self.thread_list_frame = Frame(self.thread_list_canvas)

        # Creates scroll bar
        self.vsb = Scrollbar(self.root, orient="vertical", command=self.thread_list_canvas.yview)
        self.thread_list_canvas.configure(yscrollcommand=self.vsb.set)
        self.vsb.pack(side="right", fill="y")

        self.hsb = Scrollbar(self.root, orient="horizontal", command=self.thread_list_canvas.xview)
        self.thread_list_canvas.configure(xscrollcommand=self.hsb.set)
        self.hsb.pack(side="bottom", fill="x")

        # Packs frame
        self.thread_list_canvas.pack(side="left", fill="both", expand=True)
        self.thread_list_canvas.create_window((4, 4), window=self.thread_list_frame, anchor="nw", tags="self.frame")
        self.thread_list_frame.bind("<Configure>", self.OnFrameConfigure)

        self.create_thread_list_box()

    def OnFrameConfigure(self, event):
        """Reset the scroll region to encompass the inner frame"""
        self.thread_list_canvas.configure(scrollregion=self.thread_list_canvas.bbox("all"))

    # noinspection PyAttributeOutsideInit
    def create_thread_list_box(self):
        """ Creates the message list box for the create method """

        def hover_on(widget):
            widget['fg'] = 'dark blue'
            # widget['underline'] = True

        def hover_off(widget):
            widget['fg'] = 'black'
            # widget['underline'] = False

        for individual_thread in self.MESSAGE_THREADS:  # Fetch Message List from model

            if individual_thread.is_valid_thread():
                self.bg_color = 'green'
            else:
                self.bg_color = 'red'

            self.individual_thread_frame = Frame(self.thread_list_frame,
                                                 bg=self.bg_color)  # Create frame for each thread

            rowToInsertAt = self.MESSAGE_THREADS.index(individual_thread)

            self.text_color = 'black'
            self.threadText = Label(self.individual_thread_frame, bg=self.bg_color, fg=self.text_color)
            self.threadText['text'] = "[ Thread #:  " + individual_thread.threadId + " ]"

            self.threadText.bind("<Enter>", lambda event, text=self.threadText: hover_on(text))
            self.threadText.bind("<Leave>", lambda event, text=self.threadText: hover_off(text))

            self.threadText.bind("<Button-1>",
                                 lambda event, thread_in=individual_thread: self.open_in_web_browser(thread_in))
            self.threadText.grid(column=0, row=0, sticky='w', padx=0)

            self.image_count_text = Label(self.individual_thread_frame, bg=self.bg_color)
            num_of_images = individual_thread.get_number_of_images()
            if 0 < int(num_of_images) < 10:  # Format padding
                num_of_images = '00' + num_of_images
            if 10 < int(num_of_images) < 100:  # Format padding
                num_of_images = '0' + num_of_images

            self.image_count_text['text'] = "  [ # Images: " + num_of_images + " ]"
            self.image_count_text.bind("<Enter>", lambda event, text=self.image_count_text: hover_on(text))
            self.image_count_text.bind("<Leave>", lambda event, text=self.image_count_text: hover_off(text))

            self.image_count_text.bind("<Button-1>",
                                       lambda event, thread_in=individual_thread: self.open_in_file_browser(thread_in))

            self.image_count_text.grid(column=1, row=0, sticky='e', padx=0)

            self.deleteButton = Button(self.individual_thread_frame)
            self.deleteButton['text'] = 'Delete'
            self.deleteButton['command'] = lambda thread_in=individual_thread: self.delete_thread_GUI(thread_in)
            self.deleteButton.grid(column=2, row=0, sticky='e', padx=0)

            self.individual_thread_frame.grid(row=rowToInsertAt, sticky='w', pady=2)

    @staticmethod
    def open_in_file_browser(individual_thread):
        logging.debug(os.getcwd() + os.sep + individual_thread.threadId)
        if os.name == "nt":
            subprocess.Popen('explorer "' + os.getcwd() + os.sep + individual_thread.threadId + '"')

    @staticmethod
    def open_in_web_browser(individual_thread):
        webbrowser.open(
            url="http://boards.4chan.org/" + individual_thread.board + "/thread/" + individual_thread.threadId, new=2)

    def add_thread_GUI(self):
        entry_box_text = str(self.thread_entry_box.get())
        if entry_box_text not in self.MESSAGE_THREADS and entry_box_text != self.DEFAULT_THREAD_TEXT \
                and entry_box_text.isnumeric():
            try:
                self.add_thread(entry_box_text.strip(' '))
            except ThreadNotFound:
                messagebox.showwarning(message="Thread Not Found")
        else:
            messagebox.showwarning(message="Please enter a valid new thread ID")
        self.thread_entry_box.select_range(start=0, end=99)
        # Selects the contents so the user can just type the next message
        self.refresh_GUI()

    def delete_thread_GUI(self, thread_in):
        self.delete_thread(thread_in)
        self.refresh_GUI()

    def refresh_GUI(self):
        """ Refreshes the message list AND GUI window (used by auto refresh)"""
        self.refresh_thread_list()
        self.refresh_GUI_Window()

    def refresh_GUI_Window(self):
        """ Refreshes just the GUI window"""
        self.thread_list_canvas.destroy()
        self.vsb.destroy()
        self.hsb.destroy()
        self.create_thread_frame()

    @staticmethod
    def program_about():
        message = settings.__desc__ + '\n' + settings.__version__
        messagebox.showinfo(title='About', message=message)

    @staticmethod
    def program_help():
        message = 'See readme.md'
        messagebox.showinfo(title='About', message=message)
示例#42
0
    def __init__(self, master, columns, column_weights=None, cnf={}, **kw):
        """
        Construct a new multi-column listbox widget.

        :param master: The widget that should contain the new
            multi-column listbox.

        :param columns: Specifies what columns should be included in
            the new multi-column listbox.  If ``columns`` is an integer,
            the it is the number of columns to include.  If it is
            a list, then its length indicates the number of columns
            to include; and each element of the list will be used as
            a label for the corresponding column.

        :param cnf, kw: Configuration parameters for this widget.
            Use ``label_*`` to configure all labels; and ``listbox_*``
            to configure all listboxes.  E.g.:

                >>> mlb = MultiListbox(master, 5, label_foreground='red')
        """
        # If columns was specified as an int, convert it to a list.
        if isinstance(columns, int):
            columns = list(range(columns))
            include_labels = False
        else:
            include_labels = True

        if len(columns) == 0:
            raise ValueError("Expected at least one column")

        # Instance variables
        self._column_names = tuple(columns)
        self._listboxes = []
        self._labels = []

        # Pick a default value for column_weights, if none was specified.
        if column_weights is None:
            column_weights = [1] * len(columns)
        elif len(column_weights) != len(columns):
            raise ValueError('Expected one column_weight for each column')
        self._column_weights = column_weights

        # Configure our widgets.
        Frame.__init__(self, master, **self.FRAME_CONFIG)
        self.grid_rowconfigure(1, weight=1)
        for i, label in enumerate(self._column_names):
            self.grid_columnconfigure(i, weight=column_weights[i])

            # Create a label for the column
            if include_labels:
                l = Label(self, text=label, **self.LABEL_CONFIG)
                self._labels.append(l)
                l.grid(column=i, row=0, sticky='news', padx=0, pady=0)
                l.column_index = i

            # Create a listbox for the column
            lb = Listbox(self, **self.LISTBOX_CONFIG)
            self._listboxes.append(lb)
            lb.grid(column=i, row=1, sticky='news', padx=0, pady=0)
            lb.column_index = i

            # Clicking or dragging selects:
            lb.bind('<Button-1>', self._select)
            lb.bind('<B1-Motion>', self._select)
            # Scroll whell scrolls:
            lb.bind('<Button-4>', lambda e: self._scroll(-1))
            lb.bind('<Button-5>', lambda e: self._scroll(+1))
            lb.bind('<MouseWheel>', lambda e: self._scroll(e.delta))
            # Button 2 can be used to scan:
            lb.bind('<Button-2>', lambda e: self.scan_mark(e.x, e.y))
            lb.bind('<B2-Motion>', lambda e: self.scan_dragto(e.x, e.y))
            # Dragging outside the window has no effect (diable
            # the default listbox behavior, which scrolls):
            lb.bind('<B1-Leave>', lambda e: 'break')
            # Columns can be resized by dragging them:
            l.bind('<Button-1>', self._resize_column)

        # Columns can be resized by dragging them.  (This binding is
        # used if they click on the grid between columns:)
        self.bind('<Button-1>', self._resize_column)

        # Set up key bindings for the widget:
        self.bind('<Up>', lambda e: self.select(delta=-1))
        self.bind('<Down>', lambda e: self.select(delta=1))
        self.bind('<Prior>', lambda e: self.select(delta=-self._pagesize()))
        self.bind('<Next>', lambda e: self.select(delta=self._pagesize()))

        # Configuration customizations
        self.configure(cnf, **kw)
示例#43
0
class Photo(Widget):

	def __init__(self, **kwargs):

		try:
			self.repr = kwargs['repr']
			self.path = kwargs['path']
		except:
			print("widget could not be loaded")

		#self.script_dir = os.path.dirname(os.path.abspath(__file__))
		self.width = 200
		self.height = 200


	def config(self, **kwargs):

		try:
			self.path = kwargs['path']
			self.picture = Image.open(self.path)
			if 'resize_portr' in kwargs:
				self.picture = self.picture.resize((200, 200), Image.ANTIALIAS)
			self.image = ImageTk.PhotoImage(self.picture)
			self.label.config(image=self.image)
		except:
			pass
			#print("the widget could not be configured")

		try:
			self.bgc = kwargs['bg']
			self.label.config(bg=self.bgc)
		except:
			pass
			#print("the widget background color could not be changed")


	def trytoplace(self, **kwargs):
		self.parent = kwargs['parent']
		self.row = kwargs['row']
		self.column = kwargs['column']


	def place(self, **kwargs):

		try:
			self.trytoplace(**kwargs)
		except:
			print("widget could not be placed")

		self.picture = Image.open(self.path)
		self.image = ImageTk.PhotoImage(self.picture)

		self.label = Label(self.parent, image=self.image, bd=1)#, bg='black')
		self.label.grid(row=self.row, column=self.column, pady=5)
		self.label.bind('<Button-1>', lambda e: self.label.focus_set())


	def getData(self):
		return self.path


	def setData(self, data):
		#le sigh
		if data == '' or 'N/A': return
		self.config(path=data, resize_portr=True)


	def hide(self):
		self.label.grid_forget()
示例#44
0
class Frontend():
    def __init__(self,x,y,b):
        self.x=str(x)   #1600
        self.y=str(y)   #900
        self.pressed=0
        self.b=10
        self.c=30
        self.grapher=0
        self.graph=[0,0,0,0]
        self.root=b
    def startwindow(self):
       # self.root=Tk()
        a=str(self.x+'x'+self.y)
        self.root.title('Wahrscheinlichkeinten & Simulation')
        self.root.geometry(a)
        self.g=Label(self.root,bg='white')
        self.g.place(x=0,y=0,width=self.x,height=self.y)
       # self.g.bind('<1>',self.optioncanged)
        self.lst1 = ['Marriage','Atom','BubbleGum','House_of_Cards','Lotto','SecretSanta','Coins']
        self.var1 = StringVar(self.root)
        self.var1.set('Marriage')
        self.drop = OptionMenu(self.root,self.var1,*self.lst1)
        self.drop.config(font=('Arial',(30)),bg='white')
        self.drop['menu'].config(font=('calibri',(20)),bg='white')
        self.drop.pack(side=TOP)
        self.photo = PhotoImage(file='z1.gif')
        self.label = Label(image=self.photo,borderwidth=0)
        self.label.image = self.photo
        self.label.bind('<1>',self.MouseOneDown)
        self.label.place(y=0,x=int(self.x)-200)
        self.startbutton=Button(self.root,text='Start',font=('Arial',40),bg='#B4045F',borderwidth=5,command=self.startpressed)       
        self.startbutton.place(x=0,y=int(self.y)-100,width=int(self.y)-200,height=100)
        self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='green',borderwidth=5,command=self.csvpressed)     
        self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100)
    def startpressed(self):
            if self.grapher==1:
                for x in range(len(self.graph)):
                    if self.graph[x]!=0:
                        self.graph[x].destroy()
                self.grapher=0
                self.root.update()
            a=self.var1.get()
            if self.pressed==1:
                try:
                    self.b=int(self.changer0.get('1.0','end-1c'))
                except (AttributeError,TclError,ValueError):
                    self.b=10
                try:
                    self.c=self.changer2.get('1.0','end-1c')
                except (AttributeError,TclError,ValueError):
                    self.c=1
            if a=='Marriage':
                self.run0=Marriage(self.b)
                self.run0.DEBUG=False
                self.run0.sim()
            elif a=='Atom':
                self.c=float(self.c)
                self.run1=Atom(self.c,self.b)
                self.run1.DEBUG=False
                self.run1.sim()
            elif a=='BubbleGum':
                self.run2=BubbleGum(self.b)
                self.run2.DEBUG=False
                self.run2.sim()
                self.grapher=1
                self.graph=[0,0]
                g=str(round(self.run2.getrel()[0],4))
                h=str(round(self.run2.getrel()[1],4))
                self.graph[0]=Label(self.root,bg='white',text='Durchschnitt Karten zu viel: '+g,font=('calibri',19))
                self.graph[0].place(x=10,y=450)
                self.graph[1]=Label(self.root,bg='white',text='Durchschnitt dass es passiert: '+h,font=('calibri',19))
                self.graph[1].place(x=10,y=500)
            elif a=='House_of_Cards':
                if self.c=='':
                    self.c=0
                else:
                    self.c=int(self.c)
                self.run3=House_of_Cards(self.b,self.c)
                self.run3.DEBUG=False
                self.run3.sim()
                self.grapher=1
                self.graph=[0]
                self.graph[0]=Label(self.root,bg='white',text=('Durchschnitt: '+str(round(self.run3.getrel(),4))),font=('calibri',19))
                self.graph[0].place(x=10,y=450)
            elif a=='Lotto':
                self.run4=Lotto(self.b)
                self.run4.DEBUG=False
                self.run4.sim()
                x=4
                y=1
                count=0
                self.graph=[0,0,0,0]
                self.grapher=1
                self.graph[0]=Label(self.root,bg='black')
                self.graph[0].place(x=10,width=10+(int(self.x)*0.8),height=1,y=int(self.y)-int(self.y)/4*0.5-350)
                self.graph[1]=Label(self.root,text='50%',bg='white',font=('calibri',10))
                self.graph[1].place(x=60+(int(self.x)*0.8),width=50,height=50,y=int(self.y)-int(self.y)/4*0.5-375)
                self.graph[2]=Label(self.root,bg='black')
                self.graph[2].place(x=10,width=20,height=1,y=int(self.y)-350)
                self.graph[3]=Label(self.root,bg='black')
                self.graph[3].place(x=10,width=20,height=1,y=int(self.y)-int(self.y)/4-350)
                for draw in self.run4.turns:
                    if draw.count(0) == 0:
                        count += 1
                    elif draw.count(1) == 0:
                        count += 1
                    elif draw.count(2) == 0:
                        count += 1
                    elif draw.count(3) == 0:
                        count += 1
                    elif draw.count(4) == 0:
                        count += 1
                    elif draw.count(5) == 0:
                        count += 1
                    self.graph+=[0]
                    self.graph[x]=Label(self.root,bg='red')
                    if str(self.c)=='1':
                        self.graph[x].place(x=int(10+(int(self.x)*0.8)*((y-1)/self.b)),width=int(1250/self.b),height=int(self.y)-350-(int(int(self.y)-int(self.y)/4*(count/y)-350)),y=int(int(self.y)-int(self.y)/4*(count/y)-350))
                    else:
                        self.graph[x].place(x=int(10+(int(self.x)*0.8)*(y/self.b)),width=3,height=3,y=int(int(self.y)-int(self.y)/4*(count/y)-350))
                    x+=1
                    y+=1
                    self.root.update()
            elif a=='SecretSanta':
                if self.c=='':
                    self.c=1
                else:
                    self.c=int(self.c)
                self.run5=SecretSanta(self.b,self.c)
                self.run5.DEBUG=False
                self.run5.sim()
                self.grapher=1
                self.graph=[0]
                self.graph[0]=Label(self.root,bg='white',text=('Durchschnitt: '+str(round(self.run5.getrel(),4))),font=('calibri',19))
                self.graph[0].place(x=10,y=450)
            elif a=='Coins':
                self.run6=Coins(self.b)
                self.run6.sim()
                self.grapher=1
                self.graph=[0,0]
                v=self.run6.geterg()
                vv=self.run6.getrel()
                self.graph[0]=Label(self.root,bg='white',text=('Statistik für www: '+str(v[0])+'    '+str(vv[0])),font=('calibri',19))
                self.graph[0].place(x=10,y=450)
                self.graph[1]=Label(self.root,bg='white',text=('Statistik für zwz:   '+str(v[1])+'    '+str(vv[1])),font=('calibri',19))
                self.graph[1].place(x=10,y=500)
    def csvpressed(self):
        a=self.var1.get()
        if a=='Marriage':
            self.run0.exportcsv('Marriage_Simulation.csv')
        elif a=='Atom':
            self.run1.exportCSV('Atom_Simulation.csv')
        elif a=='Lotto':
            self.run4.exportCSV('Lotto_Simulation.csv')
  #  def optioncanged(self,event):
  #          a=self.var1.get()
   #         if a=='Marriage':
    #            self.csvbutton.destroy()
     #           self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='green',borderwidth=5,command=self.csvpressed)     
          #      self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100)
      #      elif a=='Atom':
       #         self.csvbutton.destroy()
        #        self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='green',borderwidth=5,command=self.csvpressed)     
         #       self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100)
#            elif a=='BubbleGum':
 #               self.csvbutton.destroy()
  #              self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='gray',borderwidth=5)     
   #             self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100)
    #        elif a=='House_of_Cards':
     #           self.csvbutton.destroy()
      #          self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='gray',borderwidth=5)     
       #         self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100)
        #    elif a=='Lotto':
         #       self.csvbutton.destroy()
          #      self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='green',borderwidth=5,command=self.csvpressed)     
           #     self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100)
            #elif a=='SecretSanta':
   #             self.csvbutton.destroy()
    #            self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='gray',borderwidth=5)     
     #           self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100)
    def MouseOneDown(self,event):
        if self.pressed==0:
            a=self.var1.get()
            if a=='Marriage':
                self.changer0=Text(self.root,bg='white',font=('Arial',30),borderwidth=1)
                self.changer0.place(y=100,x=int(self.x)-150,width=100,height=50)
                self.changer1=Label(self.root,text='Versuche:',bg='white',font=('Arial',30),borderwidth=1)
                self.changer1.place(y=100,x=int(self.x)-400,width=250,height=50)
                self.csvbutton.destroy()
                self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='green',borderwidth=5,command=self.csvpressed)     
                self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100)
            elif a=='Atom':
                self.changer0=Text(self.root,bg='white',font=('Arial',30),borderwidth=1)
                self.changer0.place(y=100,x=int(self.x)-150,width=100,height=50)
                self.changer1=Label(self.root,text='Anzahl der Atome:',bg='white',font=('Arial',30),borderwidth=1)
                self.changer1.place(y=100,x=int(self.x)-600,width=450,height=50)
                self.changer2=Text(self.root,bg='white',font=('Arial',30),borderwidth=1)
                self.changer2.place(y=200,x=int(self.x)-150,width=100,height=50)
                self.changer3=Label(self.root,text='Zerfallswahrscheinlichkeit:',bg='white',font=('Arial',30),borderwidth=1)
                self.changer3.place(y=200,x=int(self.x)-650,width=500,height=50)
                self.csvbutton.destroy()
                self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='green',borderwidth=5,command=self.csvpressed)     
                self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100)
            elif a=='BubbleGum':
                self.changer0=Text(self.root,bg='white',font=('Arial',30),borderwidth=1)
                self.changer0.place(y=100,x=int(self.x)-150,width=100,height=50)
                self.changer1=Label(self.root,text='Versuche:',bg='white',font=('Arial',30),borderwidth=1)
                self.changer1.place(y=100,x=int(self.x)-400,width=250,height=50)
                self.csvbutton.destroy()
                self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='gray',borderwidth=5)     
                self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100)
            elif a=='House_of_Cards':
                self.changer0=Text(self.root,bg='white',font=('Arial',30),borderwidth=1)
                self.changer0.place(y=100,x=int(self.x)-150,width=100,height=50)
                self.changer1=Label(self.root,text='Versuche:',bg='white',font=('Arial',30),borderwidth=1)
                self.changer1.place(y=100,x=int(self.x)-400,width=250,height=50)
                self.changer2=Text(self.root,bg='white',font=('Arial',30),borderwidth=1)
                self.changer2.place(y=200,x=int(self.x)-150,width=100,height=50)
                self.changer3=Label(self.root,text='Kartenanzahl(32,55):',bg='white',font=('Arial',30),borderwidth=1)
                self.changer3.place(y=200,x=int(self.x)-620,width=450,height=50)
                self.csvbutton.destroy()
                self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='gray',borderwidth=5)     
                self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100)
            elif a=='Lotto':
                self.changer0=Text(self.root,bg='white',font=('Arial',30),borderwidth=1)
                self.changer0.place(y=100,x=int(self.x)-150,width=100,height=50)
                self.changer1=Label(self.root,text='Versuche:',bg='white',font=('Arial',30),borderwidth=1)
                self.changer1.place(y=100,x=int(self.x)-400,width=250,height=50)
                self.changer2=Text(self.root,bg='white',font=('Arial',30),borderwidth=1)
                self.changer2.place(y=200,x=int(self.x)-150,width=100,height=50)
                self.changer3=Label(self.root,text='Version:',bg='white',font=('Arial',30),borderwidth=1)
                self.changer3.place(y=200,x=int(self.x)-400,width=250,height=50)
                self.csvbutton.destroy()
                self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='green',borderwidth=5,command=self.csvpressed)     
                self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100)
            elif a=='SecretSanta':
                self.changer0=Text(self.root,bg='white',font=('Arial',30),borderwidth=1)
                self.changer0.place(y=100,x=int(self.x)-150,width=100,height=50)
                self.changer1=Label(self.root,text='Versuche:',bg='white',font=('Arial',30),borderwidth=1)
                self.changer1.place(y=100,x=int(self.x)-400,width=250,height=50)
                self.changer2=Text(self.root,bg='white',font=('Arial',30),borderwidth=1)
                self.changer2.place(y=200,x=int(self.x)-150,width=100,height=50)
                self.changer3=Label(self.root,text='Anzahl der Schüler:',bg='white',font=('Arial',30),borderwidth=1)
                self.changer3.place(y=200,x=int(self.x)-550,width=400,height=50)
                self.csvbutton.destroy()
                self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='gray',borderwidth=5)     
                self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100)
            elif a=='Coins':
                self.changer0=Text(self.root,bg='white',font=('Arial',30),borderwidth=1)
                self.changer0.place(y=100,x=int(self.x)-150,width=100,height=50)
                self.changer1=Label(self.root,text='Versuche:',bg='white',font=('Arial',30),borderwidth=1)
                self.changer1.place(y=100,x=int(self.x)-400,width=250,height=50)
                self.csvbutton.destroy()
                self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='gray',borderwidth=5)     
                self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100)
            self.pressed=1
        else:
            try:
                self.c=self.changer2.get('1.0','end-1c')
                self.changer3.destroy()
                self.changer2.destroy()
            except (AttributeError,TclError):
                    z=0
            try:
                self.b=self.changer0.get('1.0','end-1c')
                self.changer1.destroy()
                self.changer0.destroy()
            except (AttributeError,TclError):
                    z=0
            if self.b=='':
                self.b=1
            else:
                self.b=int(self.b)
            if self.c=='':
                self.c=1
            else:
                self.c=int(float(self.c))
            self.pressed=0
示例#45
0
    def view_details(self, Medikom, id):
        self.selected_id = id
        self.overview(Medikom)
        entry_results, attachments = Medikom.get_entry(id)
        ts, title, notes = entry_results
        ts = self.format_ts(ts)[:-3]
        details_text = 'Details zu %s (zuletzt geändert am %s)' % (title, ts)
        details_label = Label(
            self, text=details_text, font='Liberation 10', fg='Black', anchor='w')
        details_label.place(
            x=self.SPACE_TWO,
            y=(self.n + 2) * (self.ROW_HIGHT + self.ROW_SPACE),
            width=self.WIN_WIDTH - self.SPACE_TWO, height=self.ROW_HIGHT)

        details_label.bind(sequence='<Button-1>',
            func=Callable(self.view_edit_title, Medikom, id, title))

        # add attachment button and list attachments
        attach_button = Button(
            self, text='Neuer Anhang',
            command=lambda: self.attach_file(Medikom, id))
        attach_button.place(
            x=self.SPACE_TWO,
            y=(self.n + 3) * (self.ROW_HIGHT + self.ROW_SPACE),
            width=self.WIN_WIDTH / 8, height=self.ROW_HIGHT)
        if attachments:
            xpos = (1.5 * self.SPACE_TWO) + (self.WIN_WIDTH / 8)
            for i, attachment in enumerate(attachments):
                attachment = attachment[0]
                filename = ''
                if '\\' in attachment:
                    filename = attachment.split('\\')[-1]
                elif '/' in attachment:
                    filename = attachment.split('/')[-1]
                width = len(filename) * 7.2
                attachment_button = Button(
                    self, text=filename, font='Courier 9', fg="blue",
                    command=Callable(self.open_attachment, attachment))
                attachment_button.place(
                    x=xpos,
                    y=(self.n + 3) * (self.ROW_HIGHT + self.ROW_SPACE),
                    width=width, height=self.ROW_HIGHT)
                xpos = xpos + width + (self.SPACE_TWO/2)
                attachment_button.config(relief='flat')
                attachment_button.bind(sequence='<Button-3>',
                    func=Callable(self.unattach_file, Medikom, id, attachment))

        # text element and scrollbar
        textframe = Text(
            self, font='Liberation 12', height=self.TEXT_FRAME_LINES,
            width=int(self.WIN_WIDTH / 4))
        scrollbar = Scrollbar(self)
        textframe.place(
            x=self.SPACE_TWO,
            y=(self.n + 4) * (self.ROW_HIGHT + self.ROW_SPACE),
            width=self.WIN_WIDTH - self.SPACE_ONE - 10,
            height=self.ROW_HIGHT * self.TEXT_FRAME_LINES)
        scrollbar.place(
            x=self.SPACE_TWO + self.WIN_WIDTH - self.SPACE_ONE - 10,
            y=(self.n + 4) * (self.ROW_HIGHT + self.ROW_SPACE),
            width=10,
            height=self.ROW_HIGHT * self.TEXT_FRAME_LINES)
        scrollbar.config(command=textframe.yview)
        textframe.config(yscrollcommand=scrollbar.set)
        textframe.insert(END, notes)

        # update button
        update_button = Button(
            self, text='Text Aktualisieren',
            command=lambda: self.update_entry_notes(
                Medikom, id, textframe.get(1.0, END)))
        update_button.place(
            x=self.WIN_WIDTH / 2 - 0.125 * self.WIN_WIDTH,
            y=(self.n + 4) * (self.ROW_HIGHT + self.ROW_SPACE) + (self.ROW_HIGHT * self.TEXT_FRAME_LINES + 5),
            width=self.WIN_WIDTH/4, height=self.ROW_HIGHT)
示例#46
-1
 def initUI(self):
     #top frame using all the remaining space
     innerTopFrame = Frame(self, background="black")
     innerTopFrame.pack(fill=BOTH, expand=1)
     #CLOSE Label
     innerBottomLeftFrame = Frame(self, background="black")
     innerBottomLeftFrame.place(x=0, width=self.wRoot/2, 
         y=self.hRoot-200, height=200)
     closeLabel = Label(innerBottomLeftFrame, bg="black", fg="black",
         text="CLOSE", font=("Comic Sans MS", 48, "bold"))
     innerBottomLeftFrame.bind("<Enter>", lambda f: closeLabel.config(fg="white"))
     innerBottomLeftFrame.bind("<Leave>", lambda f: closeLabel.config(fg="black"))
     innerBottomLeftFrame.bind("<Button-1>", lambda f: self.root.quit())
     closeLabel.bind("<Button-1>", lambda f: self.root.quit())
     closeLabel.pack(fill=BOTH)
     #SHUT DOWN Label
     innerBottomRightFrame = Frame(self, background="black")
     innerBottomRightFrame.place(x=self.wRoot/2, width=self.wRoot/2, 
         y=self.hRoot-200, height=200)
     shutdownLabel = Label(innerBottomRightFrame, bg="black", fg="black",
         text="SHUT DOWN", font=("Comic Sans MS", 48, "bold"))
     innerBottomRightFrame.bind("<Enter>", lambda f: shutdownLabel.config(fg="white"))
     innerBottomRightFrame.bind("<Leave>", lambda f: shutdownLabel.config(fg="black"))
     innerBottomRightFrame.bind("<Button-1>", self.shutdown)
     shutdownLabel.bind("<Button-1>", self.shutdown)
     shutdownLabel.pack(fill=BOTH)
     #design the FullScreenApp
     self.pack(fill=BOTH, expand=1)
示例#47
-1
 def __makeWidgets(self):
     Label(self, text="Welcome to PyMath 0.3!\n", justify="center").pack()
     Label(self, text="Use the tabs to navigate between PyMath's different functions.", justify="center").pack()
     l = Label(self, text="About/Help", fg="blue", padx=10, pady=10)
     l.pack(side=BOTTOM, anchor=SE)
     l.config(cursor="hand2")
     l.bind("<Button-1>", self.showabout)