示例#1
0
    def body(self, master):
        """
        GUI description
        """
        self.title("Edit Region")
        
        Label(master,
              text='tag:').grid(row=0, sticky=W)
        Label(master,
              text='Maximum Triangle Area').grid(row=1, sticky=W)


        tagVar = StringVar()
        tagVar.set(self.tag)
        self.tagstr   = Entry(master,
                                   width = 16,
                                   textvariable = tagVar,
                                   takefocus=1)

    
        maxAreaVar = StringVar()
        if self.maxArea is None:
          self.maxArea = ""  
        maxAreaVar.set(self.maxArea)
        self.maxAreastr   = Entry(master,
                                   width = 16,
                                   textvariable = maxAreaVar,
                                   takefocus=1)

        self.tagstr.grid(row=0, column=1, sticky=W)
        self.maxAreastr.grid(row=1, column=1, sticky=W)

        self.tag  = -1
        self.maxArea  = -1
        self.ValueOk = False
    def CreateWidgets(self):
        self.name = StringVar(self)
        self.fontSize = StringVar(self)
        self.frameMain = Frame(self, borderwidth=2, relief=SUNKEN)
        self.messageInfo = Label(self.frameMain, text=self.message)
        entryName = Entry(self.frameMain, textvariable=self.name, width=30)
        frameButtons = Frame(self)
        self.buttonOk = Button(frameButtons, text='Ok', command=self.Ok)
        self.buttonCancel = Button(frameButtons, text='Cancel',
                command=self.Cancel)

        entryName.focus_set()

        self.frameMain.pack(side=TOP, expand=True, fill=BOTH)
        self.messageInfo.pack(padx=5, pady=5)
        entryName.pack(padx=5, pady=5)
        frameButtons.pack(side=BOTTOM, fill=X)
        self.buttonOk.pack(padx=1, pady=5, side=RIGHT)
        self.buttonCancel.pack(pady=5, padx=5, side=RIGHT)

        if TTK:
            self.messageInfo['padding'] = 5
            frameButtons['style'] = 'RootColor.TFrame'
        else:
            self.messageInfo.configure(padx=5, pady=5)
示例#3
0
	def initGUI(self):
		self.parent.title("Spark Core control")
		self.pack()

		# Initialize Entry widget for device_id and access_token
		self.frmDeviceId = Frame(self)
		self.frmDeviceId.pack()
		self.lblDeviceId = Label(self.frmDeviceId, text="Device ID")
		self.lblDeviceId.pack(side=LEFT)
		self.DeviceId = StringVar()
		self.entryDeviceId = Entry(self.frmDeviceId, textvariable=self.DeviceId)
		self.DeviceId.set("53ff70066678505553201467")
		self.entryDeviceId.pack()

		self.frmAccessToken = Frame(self)
		self.frmAccessToken.pack()
		self.lblDeviceId = Label(self.frmAccessToken, text="Access Token")
		self.lblDeviceId.pack(side=LEFT)
		self.AccessToken = StringVar()
		self.entryAccessToken = Entry(self.frmAccessToken, textvariable=self.AccessToken)
		self.AccessToken.set("f107f8f0fd642b56a2cdf0e88b3bf597761de556")
		self.entryAccessToken.pack()


		self.btnTurnOnLed = Button(self, text="LED ON", command=self.turnLedOn)
		self.btnTurnOnLed.pack()
		self.btnTurnOffLed = Button(self, text="LED OFF", command=self.turnLedOff)
		self.btnTurnOffLed.pack()
示例#4
0
class PasswordDialog(Dialog):

    def __init__(self, title, prompt, parent):
        self.prompt = prompt
        Dialog.__init__(self, parent, title)

    def body(self, master):
        from Tkinter import Label
        from Tkinter import Entry
        from Tkinter import Checkbutton
        from Tkinter import IntVar
        from Tkinter import W

        self.checkVar = IntVar()

        Label(master, text=self.prompt).grid(row=0, sticky=W)

        self.e1 = Entry(master)

        self.e1.grid(row=0, column=1)

        self.cb = Checkbutton(master, text="Save to keychain", variable=self.checkVar)
        self.cb.pack()
        self.cb.grid(row=1, columnspan=2, sticky=W)
        self.configure(show='*')

    def apply(self):
        self.result = (self.e1.get(), self.checkVar.get() == 1)
示例#5
0
    def __init__(self, master, title, prompt, x_name, y_name, var_type, x_default, y_default, *args, **kwargs):
        Toplevel.__init__(self, master, *args, **kwargs)
        self.title(title)

        #TODO: Can this be done in a smarter manner?
        self._x_var = var_type(self)
        self._y_var = var_type(self)
        self._x_var.set(x_default)
        self._y_var.set(y_default)
        self.canceled = True

        self.prompt_label = Label(self, text=prompt)
        self.prompt_label.grid(row=0, column=0, columnspan=2, pady=2)

        self.x_label = Label(self, text="{}:".format(x_name))
        self.x_input = Entry(self, textvariable=self._x_var)
        self.y_label = Label(self, text="{}:".format(y_name))
        self.y_input = Entry(self, textvariable=self._y_var)

        self.x_label.grid(row=1, column=0, pady=2)
        self.x_input.grid(row=1, column=1, pady=2)
        self.y_label.grid(row=2, column=0, pady=2)
        self.y_input.grid(row=2, column=1, pady=2)

        self.ok_button = Button(self, text="OK", command=self.ok, width=self.BUTTON_WIDTH)
        self.cancel_button = Button(self, text="Cancel", command=self.cancel, width=self.BUTTON_WIDTH)
        self.ok_button.grid(row=3, column=0, sticky="NS", padx=5, pady=2)
        self.cancel_button.grid(row=3, column=1, sticky="NS", padx=5, pady=2)
示例#6
0
    def __init__(self, master=None):
        Observable.__init__(self)
        hashText = StringVar()
        
        hashText.trace("w", lambda nm, idx, mode, var=hashText: self.textChanged(hashText))

        Entry.__init__(self, master, textvariable = hashText)
示例#7
0
    def __init__(self, parent, projects, onCreation=None):
        Frame.__init__(self, parent)

        self.onCreation = onCreation

        self.time = StringVar()
        self.time.set("00:00:00")
        self.timeEntry = None

        self.projects = projects.values()
        self.projects.sort(key=lambda x: x.name)

        l = Label(self, text="Description")
        l.grid(row=0, column=0)

        self.description = StringVar()
        e = Entry(self, textvariable=self.description, font=("Helvetica", 16))
        e.grid(row=1, column=0)

        l = Label(self, text="Project")
        l.grid(row=0, column=1)

        values = map(lambda x: x.name, self.projects)
        self.projectChooser = Combobox(self, values=values, font=("Helvetica", 16))
        self.projectChooser.grid(row=1, column=1)

        self.timeEntryClock = Label(self, textvariable=self.time, font=("Helvetica", 16))
        self.timeEntryClock.grid(row=1, column=2)

        self.submitText = StringVar()
        self.submitText.set("Start")
        self.submit = Button(self, textvariable=self.submitText, command=self.start, font=("Helvetica", 16))
        self.submit.grid(row=1, column=3, padx=10)
示例#8
0
 def CreateWidgets(self):
     self.menu = StringVar(self)
     self.path = StringVar(self)
     self.fontSize = StringVar(self)
     self.frameMain = Frame(self, borderwidth=2, relief=GROOVE)
     self.frameMain.pack(side=TOP, expand=TRUE, fill=BOTH)
     labelMenu = Label(self.frameMain, anchor=W, justify=LEFT,
                       text='Menu Item:')
     self.entryMenu = Entry(self.frameMain, textvariable=self.menu,
                            width=30)
     self.entryMenu.focus_set()
     labelPath = Label(self.frameMain, anchor=W, justify=LEFT,
                       text='Help File Path: Enter URL or browse for file')
     self.entryPath = Entry(self.frameMain, textvariable=self.path,
                            width=40)
     self.entryMenu.focus_set()
     labelMenu.pack(anchor=W, padx=5, pady=3)
     self.entryMenu.pack(anchor=W, padx=5, pady=3)
     labelPath.pack(anchor=W, padx=5, pady=3)
     self.entryPath.pack(anchor=W, padx=5, pady=3)
     browseButton = Button(self.frameMain, text='Browse', width=8,
                           command=self.browseFile)
     browseButton.pack(pady=3)
     frameButtons = Frame(self)
     frameButtons.pack(side=BOTTOM, fill=X)
     self.buttonOk = Button(frameButtons, text='OK',
                            width=8, default=ACTIVE,  command=self.Ok)
     self.buttonOk.grid(row=0, column=0, padx=5,pady=5)
     self.buttonCancel = Button(frameButtons, text='Cancel',
                                width=8, command=self.Cancel)
     self.buttonCancel.grid(row=0, column=1, padx=5, pady=5)
示例#9
0
文件: sshfsgui.py 项目: dbix/FuseGUI
    def create_widgets(self):
        """ Creates labels and text fields for username, hostname, and password.
            The password field replaces the visible entry with *'s
        """
        # Labels
        self.lbl_user = Label(self, text="Username:"******"Hostname:")
        self.lbl_pawd = Label(self, text="Password:"******"Quit", command=self.quit,
                               takefocus=0)
        self.btn_mount = Button(self, text="Mount", command=self.mount_drive,
                                takefocus=1)

        # Arrange
        self.lbl_user.grid(column=0, row=0)
        self.lbl_host.grid(column=0, row=1)
        self.lbl_pawd.grid(column=0, row=2)
        self.fld_user.grid(column=1, row=0)
        self.fld_host.grid(column=1, row=1)
        self.fld_pawd.grid(column=1, row=2)
        self.btn_quit.grid(column=0, row=3)
        self.btn_mount.grid(column=1, row=3)
 def setgridsize(self, height=5, width=6):
     self.height = height
     self.width = width
     for i in range(1, height):  # Rows
         for j in range(width):  # Columns
             b = Entry(self.root, text="")
             b.grid(row=i, column=j)
示例#11
0
 def setupView(self, title="Test Auth Page", user='', pwd_ori=''):
     userVar = StringVar()
     pwdVar = StringVar()
     userInput = Entry(self,
                       textvariable=userVar,
                       width="30").grid(row=0,
                                        columnspan=2,
                                        sticky="WE")
     pwdInput = Entry(self,
                      textvariable=pwdVar,
                      show="*",
                      width="30").grid(row=1,
                                       columnspan=2,
                                       sticky="WE")
     userVar.set(user)
     pwdVar.set(pwd_ori)
     self.ok = Button(self,
                      text='Next',
                      command=lambda: self.
                      controller.setAuth(self,
                                         userInput.get(),
                                         pwdInput.get()))
     self.ok.grid(row=2, column=1, sticky="W")
     self.cancel = Button(self,
                          text='Cancel',
                          command=lambda: self.controller.quit())
     self.cancel.grid(row=2, column=0, sticky="E")
示例#12
0
class InterpretHEXDialog(tkSimpleDialog.Dialog):
    """
    A simple dialog that allows the user to
    enter 3 byte hex codes that represent
    ektapro commands and converts them to human
    readable strings.
    """

    def body(self, master):
        self.title("Interpret Ektapro HEX Command Sequence")

        self.description = Label(master, text="Please enter 3 Byte HEX Code (for example: 03 1C 00):")
        self.description.pack(side=TOP, anchor=W)

        self.hexcommand = Entry(master, width=10)
        self.hexcommand.pack(side=TOP, anchor=W)

        return self.hexcommand

    def apply(self):
        inputString = self.hexcommand.get().replace(" ", "")

        if not len(inputString) == 6:
            tkMessageBox.showerror("Error", "Please enter exactly 3 Bytes (6 Characters)!")

        else:
            b1 = int(inputString[0:2], 16)
            b2 = int(inputString[2:4], 16)
            b3 = int(inputString[4:6], 16)
            message = str(EktaproCommand(b1, b2, b3))
            tkMessageBox.showinfo("Command Result", "Interpreted Command: " + message)
示例#13
0
class searchDialog(Toplevel):
        def __init__(self, parent, title):
                self.top = Toplevel(parent)
                self.top.wm_title(title)
                self.top.wm_minsize(width=300, height=400)
                self.top.bind("<Return>", self.searchThreader)
                self.top.bind("<Escape>", self.close)

                self.searchy = Text(self.top)
                self.searchy.config(wrap=WORD)
                self.search_entry = Entry(self.top)
                self.close = Button(self.top, text="Close", command=self.close)
                self.search_button = Button(self.top,
                                            text="Search",
                                            command=self.searchThreader)
                self.scrollbar = Scrollbar(self.top)

                self.scrollbar.pack(side=RIGHT, fill=Y, expand=0)
                self.searchy.config(yscrollcommand=self.scrollbar.set,
                                    state=DISABLED)
                self.searchy.pack(side=TOP, fill=BOTH, expand=1)
                self.search_entry.pack(side=LEFT, fill=X, expand=1)
                self.close.pack(side=RIGHT, fill=BOTH, expand=0)
                self.search_button.pack(side=RIGHT, fill=BOTH, expand=0)

                self.linker = HyperlinkManager(self.searchy)

        def close(self, event=None):
                global SEARCH
                SEARCH = None
                self.top.destroy()

        def putText(self, text):
                updateDisplay(text, self.searchy, self.linker)

        def clearSearch(self):
                self.searchy.config(state=NORMAL)
                self.searchy.delete(1.0, END)
                self.searchy.config(state=DISABLED)

        def searchThreader(self, event=None, text=None):
                self.sear = upThread(6, 'search', (self, text))
                self.sear.start()

        def search(self, toSearch=None):
                if toSearch is None:
                        keyword = self.search_entry.get()
                        self.search_entry.delete(0, END)
                else:
                        keyword = toSearch
                self.clearSearch()
                self.top.wm_title("Search - " + keyword)
                if keyword.split('@')[0] == '':
                        self.putText(
                            API.GetUserTimeline(
                                screen_name=keyword.split('@')[1]
                            )
                        )
                else:
                        self.putText(API.GetSearch(term=keyword))
示例#14
0
    def body(self, parent):
        """
        Define the body of the dialog
        """
        Label(parent, text="Source:", bg="grey").grid(row=0, column=0, sticky=W)
        Label(parent, text="Target:", bg="grey").grid(row=0, column=2, sticky=W)
        Label(parent, text="Wall1:").grid(row=1, column=0, sticky=W+E, columnspan=2)
        Label(parent, text="Wall2:").grid(row=1, column=2, sticky=W+E, columnspan=2)

        # The edge options now
        self.source = Label(parent, width=9, text=self._entries["source"], bg="grey")
        self.target = Label(parent, width=9, text=self._entries["target"], bg="grey")
        self.source.grid(row=0, column=1, sticky=W)
        self.target.grid(row=0, column=3, sticky=W)

        # The wall options now
        Label(parent, text="Height:").grid(row=2, column=0, sticky=W)
        Label(parent, text="Height:").grid(row=2, column=2, sticky=W)
        self.wall1_tex_select = TexturePicker(parent, self._entries["wall1"]["textures"])
        self.wall2_tex_select = TexturePicker(parent, self._entries["wall2"]["textures"])
        self.wall1_tex_select.config(width=18)
        self.wall2_tex_select.config(width=18)
        self.wall1_tex_select.grid(row=3, columnspan=2, column=0)
        self.wall2_tex_select.grid(row=3, columnspan=2, column=2)
        self.wall1_height = Entry(parent, width=9)
        if self._entries["wall1"]["height"] is not None:
            self.wall1_height.insert(0, self._entries["wall1"]["height"])
        self.wall2_height = Entry(parent, width=9)
        if self._entries["wall2"]["height"] is not None:
            self.wall2_height.insert(0, self._entries["wall2"]["height"])
        self.wall1_height.grid(row=2, column=1)
        self.wall2_height.grid(row=2, column=3)
示例#15
0
 def make_entry(self, label, var):
     l = Label(self.top, text=label)
     l.grid(row=self.row, column=0, sticky="ne", padx=6, pady=6)
     e = Entry(self.top, textvariable=var, exportselection=0)
     e.grid(row=self.row, column=1, sticky="nwe", padx=6, pady=6)
     self.row = self.row + 1
     return e
示例#16
0
	def initUI(self):
		
		self.pack(fill=BOTH, expand=1)
		
		#create special frame for buttons at the top
		frame = Frame(self)
		frame.pack(fill=X)
		
		search = Entry(frame)
		
		def callback():
			#create new window
			main(Search.SearchFrontPage(search.get()))
		
		b = Button(frame, text="Search", width=5, command=callback)
		b.pack(side=RIGHT)
		search.pack(side=RIGHT)
		
		def login():
			#change login credentials
			self.credentials = reddituserpass.main()
			self.parent.destroy()
		
		login = Button(frame, text="Login", width=5, command=login)
		login.pack(side=LEFT)
		
		self.drawWindow()
示例#17
0
class HomunculusDirectory(Homunculus):
    def __init__(self, params):
        Homunculus.__init__(self, params[0])
        self.title(settings.HOMUNCULUS_VERSION + settings.HMC_TITLE_DIRECTORY)

        self.geometry("640x50+" + str(int(self.winfo_screenwidth()/2 - 320)) + "+" +
                      str(int(self.winfo_screenheight()/2 - 25)))
        Label(self, text="Enter directory or say 'browse'", name="pathlabel").pack()
        self.content = StringVar()
        self.word_box = Entry(self, name="word_box", width=640, textvariable=self.content)
        self.word_box.pack()

    def xmlrpc_get_message(self):
        if self.completed:
            response = {"mode": "ask_dir"}
            response["path"] = self.word_box.get()

            Timer(1, self.xmlrpc_kill).start()
            self.after(10, self.withdraw)
            return response
        else:
            return None

    def _ask_directory(self):
        dir_opt = {}
        dir_opt['initialdir'] = os.path.expanduser('~')  #os.environ["HOME"]
        dir_opt['mustexist'] = False
        dir_opt['parent'] = self
        dir_opt['title'] = 'Please select directory'
        result = tkFileDialog.askdirectory(**dir_opt)
        self.content.set(result)

    def xmlrpc_do_action(self, action, details=None):
        if action == "dir":
            self.after(10, self._ask_directory)
示例#18
0
def save(squares):
    """
    Handle the save key on the main window.
    """
    def save_button_hit():
        """
        Save key (on local window) was hit.  Save the file name entered.
        """
        text_in = save_entry.get().strip()
        if len(text_in) == 0:
            showwarning('Error', 'File name specified is empty.')
            return
        outfile = os.path.join(savedir, text_in)
        with open(outfile, 'w') as fyle:
            for sqr_info in save_squares:
                fyle.write('%d:%d:%s\n' % tuple(save_squares[sqr_info]))
        top.destroy()
    top = Toplevel()
    top.geometry('180x80+800+200')
    top.title('Save a layout')
    save_squares = squares
    savedir = getdir()
    label1 = Label(top, text='File name')
    save_entry = Entry(top)
    label1.grid(row=0)
    save_entry.grid(row=0, column=1, columnspan=2)
    save_entry.focus_set()
    save_button = Button(top, text='SAVE', pady=3,
            command=save_button_hit)
    sspace = Label(top)
    sspace.grid(row=1)
    save_button.grid(row=2, column=1)
    top.mainloop()
class MyDialog:

    def __init__(self, parent):

        top = self.top = Toplevel(parent)

        Label(top, text="Approved user names separated by a comma\nEmpty to allow all.").pack()

        self.e = Entry(top)
        self.e.pack(padx=5)
        self.APPROVED_USERS = []
        self.ALLOW_ALL = False

        b = Button(top, text="OK", command=self.ok)
        b.pack(pady=5)

    def ok(self):

        print "value is", self.e.get()
        self.APPROVED_USERS = [x.strip().lower() for x in self.e.get().split(',') if len(x.strip())>0]
        if len(self.APPROVED_USERS)==0:
        	self.ALLOW_ALL=True
        print 'APPROVED_USERS', self.APPROVED_USERS
        print 'ALLOW_ALL', self.ALLOW_ALL

        self.top.destroy()
示例#20
0
    def get_name(self):
        frame = DraggableFrame(self._root)
        frame.pack(side=TOP, fill=BOTH, expand=YES)

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

        w = self._set_frame_geo(frame, 0.3, 0.3)[2]
        self._set_x_button(frame, w, self._close_get_name)
        Label(frame, text="Name:").grid(column=1, row=1)
        entry_style = SUNKEN if self._is_osx else FLAT
        entry = Entry(frame, exportselection=0, relief=entry_style, textvariable=self._name)
        entry.grid(column=2, row=1)
        entry.focus_set()
        error_label = Label(frame, fg='red')
        error_label.grid(column=1, row=2, columnspan=3)

        ok_cmd = partial(self._validate_name, error_label)
        FlatButton(frame, text='OK', width=20, font=("calibri", 15),
                   command=ok_cmd).grid(column=1, row=3, columnspan=3)

        self._root.bind('<Return>', ok_cmd)
        self._root.bind('<Escape>', self._close_get_name)
        self._run()
        return self._name.get() if self._name else self._name
示例#21
0
class IndexWidget:

    def __init__(self, parser, prompt, url):
        self.query_url = string.joinfields(string.split(url), '')
        formatter = parser.formatter
        viewer = parser.viewer
        self.context = viewer.context
        self.w = Entry(viewer.text,
                       highlightbackground=viewer.text["background"])
        self.w.bind('<Return>', self.submit)
        formatter.add_hor_rule()
        formatter.add_flowing_data(prompt)
        formatter.add_literal_data('  ')
        parser.add_subwindow(self.w)
        formatter.add_line_break()
        formatter.add_hor_rule()

    def submit(self, event):
        data = self.w.get()
        url = self.query_url or self.context.get_baseurl()
        i = string.find(url, '?')
        if i >= 0:
            url = url[:i]
        url = url + '?' + quote(data)
        self.context.load(url)
示例#22
0
	def setTextFields(self):
		'''
			This function will set the text fields.
		'''	
		#UDP Client
		# host 
		self.udp_hostEntry = Entry(self)
		self.udp_hostEntry.insert(0, "127.0.0.1")
		self.udp_hostEntry.place(x = 90, y = 40)
		# port
		self.udp_portEntry = Entry(self)
		self.udp_portEntry.insert(0, "4001")
		self.udp_portEntry.place(x = 90, y = 70)
		
		#TCP Server
		# Host Name
		self.tcp_hostEntry = Entry(self)
		self.tcp_hostEntry.insert(0, "127.0.0.1")
		self.tcp_hostEntry.place(x = 420, y = 40)
		
		# Port
		self.tcp_portEntry = Entry(self)
		self.tcp_portEntry.insert(0, "5005")
		self.tcp_portEntry.place(x = 420, y = 70)

		# Notification period
		self.notificationEntry = Entry(self)
		self.notificationEntry.insert(0, "5")
		self.notificationEntry.place(x = 420, y = 100)
示例#23
0
	def __init__( self, main, dataInstance, axes ):
		"""Initializes the file saving dialog."""
		self.main = main
		self.dataInstance = dataInstance
		self.axes = axes
		
		self.root = Tk()
		self.root.title( "Save As CSV" )
		self.root.geometry( "350x200" )
		
		Label( self.root, text="Choose options for save." ).grid( row=0, columnspan=2 )
		
		Label(self.root, text="Filename").grid( row=1,column=0, sticky=tk.W )
		self.main.saveFileName = StringVar( self.root )
		fileNameField = Entry( self.root, textvariable=self.main.saveFileName )
		fileNameField.grid(row=1, column=1)
		
		Label( self.root, text="Number of Columns" ).grid( row=2,column=0, sticky=tk.W )
		self.main.numSaveCols = StringVar( self.root )
		self.main.numSaveCols.set( "All" )
		colNumTuple = ( "All", )
		for i in range( len(axes) ):
			colNumTuple += ( str(i+1), )
		w = apply( OptionMenu, ( self.root, self.main.numSaveCols ) + colNumTuple )
		w.grid( row=2, column=1 )
		
		def callback():
			self.root.destroy()
			if self.main.numSaveCols.get() == "All":
				self.main.writeCSVFile()
			else:
				self.columnChooser()
				
		b1 = Button( self.root, text="Confirm", command=callback )
		b1.grid( row=3, columnspan=2 )	
    def CreateWidgets(self):
        self.menu = StringVar(self)
        self.path = StringVar(self)
        self.fontSize = StringVar(self)
        self.frameMain = Frame(self, borderwidth=2, relief=GROOVE)
        labelMenu = Label(self.frameMain, anchor=W, justify=LEFT,
            text='Menu Item:')
        self.entryMenu = Entry(self.frameMain, textvariable=self.menu)
        labelPath = Label(self.frameMain, anchor=W, justify=LEFT,
            text='Help File Path: Enter URL or browse for file')
        self.entryPath = Entry(self.frameMain, textvariable=self.path,
            width=30)
        browseButton = Button(self.frameMain, text='Browse', width=8,
            command=self.browseFile)
        frameButtons = Frame(self)
        self.buttonOk = Button(frameButtons, text='OK', width=8,
            default=ACTIVE,  command=self.Ok)
        self.buttonCancel = Button(frameButtons, text='Cancel', width=8,
            command=self.Cancel)

        self.entryMenu.focus_set()

        self.frameMain.pack(side=TOP, expand=True, fill=BOTH)
        labelMenu.pack(anchor=W, padx=5, pady=3)
        self.entryMenu.pack(anchor=W, padx=5, pady=3, fill=X)
        labelPath.pack(anchor=W, padx=5, pady=3)
        self.entryPath.pack(anchor=W, padx=5, pady=3, side=LEFT, fill=X)
        browseButton.pack(pady=3, padx=5, side=RIGHT)
        frameButtons.pack(side=BOTTOM, fill=X)
        self.buttonOk.pack(pady=5, side=RIGHT)
        self.buttonCancel.pack(padx=5, pady=5, side=RIGHT)

        if TTK:
            frameButtons['style'] = 'RootColor.TFrame'
示例#25
0
	def convertChoice(self):

		#Las partes que integran el primer submenu llamado "DE", labelFrame,menu, entrada.
		self.labelFrameFrom=LabelFrame(self.master,text="De",background=R.Bgcolor)
		self.labelFrameFrom.grid(row=1,column=0,padx=5,pady=3)

		self.menuFrom=OptionMenu(self.labelFrameFrom,self.fromLabel,"",)
		self.menuFrom.configure(bg=R.White,fg=R.Black,activebackground=R.hoverBtnColor,highlightbackground=R.Bgcolor,
								indicatoron=0,image=self.btnFlechaimg, compound='right')
		self.menuFrom.grid(row=0,column=0,padx=3,pady=2,sticky=E)

		self.entryFrom=Entry(self.labelFrameFrom,justify='center',textvariable=self.fromNumber)
		self.entryFrom.grid(row=2,column=0,padx=5,pady=5)

		#Las partes que integran el segundo submenu llamado "Hasta", labelFrame, menu, entrada.

		self.labelFrameTo=LabelFrame(self.master,text="Hacia",background=R.Bgcolor)
		self.labelFrameTo.grid(row=1,column=1,padx=5,pady=3)

		self.menuTo=OptionMenu(self.labelFrameTo,self.toLabel,"",)
		self.menuTo.configure(bg=R.White,fg=R.Black, activebackground=R.hoverBtnColor,highlightbackground=R.Bgcolor,
					indicatoron=0,image=self.btnFlechaimg, compound='right')
		self.menuTo.grid(row=0,column=0, padx=3, pady=2, sticky=E)

		self.entryTo=Entry(self.labelFrameTo,justify='center',textvariable=self.toNumber,state="readonly")
		self.entryTo.configure(bg="red", readonlybackground=R.Bgcolor)
		self.entryTo.grid(row=2,column=0,padx=3,pady=5)
示例#26
0
def test_tabs():
    a = Tk()
    n = Notebook( a, TOP )

    # uses the Notebook's frame
    f1 = Frame( n() )
    b1 = Button( f1, text="Ignore me" )
    e1 = Entry( f1 )
    # pack your widgets before adding the frame 
    # to the Notebook (but not the frame itself)!
    b1.pack( fill=BOTH, expand=1 )
    e1.pack( fill=BOTH, expand=1 )

    # keeps the reference to the radiobutton (optional)
    x1 = n.add_screen( f1, "Tab 1" )

    f2 = Frame( n() )
    # this button destroys the 1st screen radiobutton
    b2 = Button( f2, text='Remove Tab 1', command=lambda:x1.destroy() )
    b3 = Button( f2, text='Beep...', command=lambda:Tk.bell( a ) )
    b2.pack( fill=BOTH, expand=1 )
    b3.pack( fill=BOTH, expand=1 )

    f3 = Frame( n() )


    n.add_screen( f2, "Tab 2" )
    n.add_screen( f3, "Minimize" )
    a.mainloop()
class RecordController(Frame):
    def __init__(self, master, *args, **kwargs):
        super(RecordController, self).__init__(master, *args, **kwargs)
        self.master = master
        self.current_record = 0
        self.create_widgets()

    def create_widgets(self):
        self.record_label = Label(self, text='Records')
        self.record_label.grid(column=1, row=1)
        self.to_beginning_button = Button(self, text='|<')
        self.to_beginning_button.grid(column=2, row=1)
        self.to_backone_button = Button(self, text='<')
        self.to_backone_button.grid(column=3, row=1)

        self.search_field = Entry(self)
        self.search_field.grid(column=4, row=1)

        self.to_fowardone_button = Button(self, text='>')
        self.to_fowardone_button.grid(column=5, row=1)
        self.to_end_button = Button(self, text='>|')
        self.to_end_button.grid(column=6, row=1)

    def on_get_record_button_press(self, event):
        if event.widget.text == '|<':
            self.current_record = 0
        elif event.widget.text == '<':
            self.current_record -= 1
            if self.current_record < 0:
                self.current_record = 0
        elif event.widget.text == '>':
            self.current_record += 1
        elif event.widget.text == '>|':
            self.current_record += 1  # TODO This isnt right for now
示例#28
0
文件: fridge.py 项目: zemlanin/fridge
	def __init__(self, master):
		rows = 10
		columns = 7
		self.d = door(rows, columns)
		master.title("The Fridge")
		self.frame = Frame(master)

		controls = Frame(self.frame)
		self.start = Button(controls,
						text = "Restart",
						width = 6,
						command = self.restart
						)
		self.start.grid(row = 0, column = 4, columnspan = 2, sticky = E)
		self.rowtext = Entry(controls, width = 4)
		self.rowtext.grid(row = 0, column = 0, columnspan = 2, sticky = W)
		self.coltext = Entry(controls, width = 4)
		self.coltext.grid(row = 0, column = 2, columnspan = 2, sticky = E)
		controls.grid(row = 0, column = 0, columnspan = 7)

		self.bttns = []
		for i in xrange(rows):
			for j in xrange(columns):
				cb = Button(self.frame,
						bg = "green" if self.d.plate[i][j].state else "red",
						text = " ",
						command = self.click(self.bttns, self.d, i, j) # coolhack
						)
				cb.grid(row = i+1, column = j)
				self.bttns.append(cb)

		self.frame.grid(column = 0, row = 0)
示例#29
0
    def __init__(self,
                 master,
                 entry_width=30,
                 entry_font=None,
                 entry_background="white",
                 entry_highlightthickness=1,
                 button_text="Search",
                 button_ipadx=10,
                 button_background="#009688",
                 button_foreground="white",
                 button_font=None,
                 opacity=0.8,
                 placeholder=None,
                 placeholder_font=None,
                 placeholder_color="grey",
                 spacing=3,
                 command=None):
        Frame.__init__(self, master)

        self._command = command

        self.entry = Entry(self,
                           width=entry_width,
                           background=entry_background,
                           highlightcolor=button_background,
                           highlightthickness=entry_highlightthickness)
        self.entry.pack(side=LEFT, fill=BOTH, ipady=1, padx=(0, spacing))

        if entry_font:
            self.entry.configure(font=entry_font)

        if placeholder:
            add_placeholder_to(self.entry,
                               placeholder,
                               color=placeholder_color,
                               font=placeholder_font)

        self.entry.bind("<Escape>",
                        lambda event: self.entry.nametowidget(".").focus())
        self.entry.bind("<Return>", self._on_execute_command)

        opacity = float(opacity)

        if button_background.startswith("#"):
            r, g, b = hex2rgb(button_background)
        else:
            # Color name
            r, g, b = master.winfo_rgb(button_background)

        r = int(opacity * r)
        g = int(opacity * g)
        b = int(opacity * b)

        if r <= 255 and g <= 255 and b <= 255:
            self._button_activebackground = '#%02x%02x%02x' % (r, g, b)
        else:
            self._button_activebackground = '#%04x%04x%04x' % (r, g, b)

        self._button_background = button_background

        self.button_label = Label(self,
                                  text=button_text,
                                  background=button_background,
                                  foreground=button_foreground,
                                  font=button_font)
        if entry_font:
            self.button_label.configure(font=button_font)

        self.button_label.pack(side=LEFT, fill=Y, ipadx=button_ipadx)

        self.button_label.bind("<Enter>", self._state_active)
        self.button_label.bind("<Leave>", self._state_normal)

        self.button_label.bind("<ButtonRelease-1>", self._on_execute_command)
示例#30
0
        def callback(result):
            global disabled
            disabled = False
            result_var.set(result)

        disabled = True
        tk_call_async(root,
                      _example_calculation,
                      args=(n.get(), ),
                      callback=callback,
                      method=MULTIPROCESSING)

    root = Tk()

    n = IntVar(value=35)
    row = Frame(root)
    row.pack()
    Entry(row, textvariable=n).pack(side=LEFT)
    Button(row, text="Calculate fibonnaci",
           command=calculate_fibonacci).pack(side=LEFT)
    Button(
        row,
        text="It's responsive",
        command=lambda: messagebox.showinfo("info", "it's responsive")).pack(
            side=LEFT)

    result_var = StringVar()
    Label(root, textvariable=result_var).pack()

    root.mainloop()
示例#31
0
##kegiatan 3

from Tkinter import Tk, Label, Button, Entry, StringVar
from tkMessageBox import showinfo

my_app=Tk(className='JAJAR GENJANG')

j1=Label(my_app, text='JAJAR GENJANG', font=('arial', 15))
j1.grid(row=0, column=0)
j2=Label(my_app, text='''Jajar genjang adalah bangun dua dimensi yang dibentuk oleh dua pasang rusuk, \n yang masing-masing sama panjang dan sejajar dengan pasangannya, serta dua pasang sudut yang sama besar dan berhadapan.''')
j2.grid(row=1, column=0)

L1=Label(my_app, text='alas')
L1.grid(row=2, column=0)
str1=StringVar()
E1=Entry(my_app, textvariable='str1')
E1.grid(row=2, column=1, columnspan=3)

L2=Label(my_app, text='tinggi')
L2.grid(row=3, column=0)
str2=StringVar()
E2=Entry(my_app, textvariable='str2')
E2.grid(row=3, column=1, columnspan=3)

def luas():
    alas=float(str1.get())
    tinggi=float(str2.get())
    luas=alas*tinggi
    HL.config(text=luas)
    
B=Button(my_app, text='Hitung Luas', command=luas)
示例#32
0
from Tkinter import Tk, Label, Entry, Button, StringVar
from tkMessageBox import showinfo

my_app = Tk(className='Luas Tabung')

L1 = Label(my_app, text='Tinggi')
L1.grid(row=0, column=0)
str1 = StringVar(value=0)
E1 = Entry(my_app)
E1.grid(row=0, column=1)

L2 = Label(my_app, text="Jari-Jari")
L2.grid(row=1, column=0)
str2 = StringVar(value=1)
E2 = Entry(my_app)
E2.grid(row=1, column=1)

L3 = Label(my_app, text='Hasil')
L3.grid(row=2, column=0)


def luas():
    T = float(str1.get())
    R = float(str2.get())
    K = 3, 14 * R**2
    G = 2 * 3, 14 * R * T
    M = 3.14 * R**2
    L = (K + G + M)


B1 = Button(my_app, text='Hitung Luas', command=luas)
示例#33
0
	def filterCase( self ):
		
		self.root = Tk()
		self.root.title('Choose Filter Options')
		
		if ( self.main.filterUse.get() == "One" ):
			filterCount = 1
		elif ( self.main.filterUse.get() == "Two" ):
			filterCount = 2
		
		winHeight = str(30+(130*filterCount))
		
		self.root.geometry('500x'+winHeight+'-80+80')
		
		localFilterList = []
		self.main.filterList = None
		
		for i in range( filterCount ):
			headerFilter = StringVar( self.root )
			exactFilter = StringVar( self.root )
			minValFilter = StringVar( self.root )
			maxValFilter = StringVar( self.root )
			
			chooseMessage = " (Choose an axis and fill in either 'Exact Value' OR the 'Max' and 'Min')"
			sectionName = "Filter "+str(i+1)+chooseMessage
			Label(self.root, text=sectionName ).grid(row=(5*i), columnspan=2)
			Label(self.root, text="Axis to Filter").grid(row=(5*i)+1, column=0, sticky=tk.W)
			Label(self.root, text="Exact Value").grid(row=(5*i)+2, column=0, sticky=tk.W)
			Label(self.root, text="Min Value").grid(row=(5*i)+3, column=0, sticky=tk.W)
			Label(self.root, text="Max Value").grid(row=(5*i)+4, column=0, sticky=tk.W)
			
			gridPlace = []
			for k in range( (5*i)+1, 5*(i+1) ):
				gridPlace.append( k )
			
			headersTuple = ()
			for i in range( len( self.dataInstance.metaData ) ):
				headersTuple = headersTuple + (self.dataInstance.metaData[i][0], )
			drop = apply( OptionMenu, (self.root, headerFilter) + headersTuple )
			drop.grid(row=gridPlace.pop(0), column=1)
			
			headerFilter.set( headersTuple[0] )

			text1 = Entry( self.root, textvariable=exactFilter )
			text1.grid(row=gridPlace.pop(0), column=1)

			text2 = Entry( self.root, textvariable=minValFilter )
			text2.grid(row=gridPlace.pop(0), column=1)

			text3 = Entry( self.root, textvariable=maxValFilter )
			text3.grid(row=gridPlace.pop(0), column=1)
			
			fieldList = [ headerFilter, exactFilter, minValFilter, maxValFilter ]
			
			localFilterList.append( fieldList )
			
		def callback():
			"""Handles the button press at the end of the filter function."""
			self.root.destroy()
			
			for i in range( len( localFilterList ) ):
				for j in range( len( localFilterList[0] ) ):
					localFilterList[i][j] = localFilterList[i][j].get()
			self.main.filterList = localFilterList
			
			if ( self.main.colorUse.get() == "Clusters" ):
				self.dataInstance.filteredSelect()
				self.clusterCase()
			else:
				self.dataInstance.filteredSelect()
				if ( self.plotType == "Scatterplot" ):
					self.dataInstance.filteredSelect()
					self.scatterBuild()
				elif ( self.plotType == "Histogram" ):
					self.histoCase()
				
			
		b1 = Button( self.root, text="Confirm Filter Preferences", command=callback )
		b1.grid( row=5*(i+1), columnspan=2 )
示例#34
0
class ChemicalImporter:
    def __init__(self, master, system, database):
        """The constructor method."""

        self.version = system.version
        self.fonttype = system.fonttype
        self.sfont = get_superfont(self.fonttype)
        self.master = master
        self.frame = Frame(master.frame)
        self.tframe = Frame(master.tframe)
        self.bframe = Frame(master.bframe)
        self.tkfont = tkFont.Font(font=system.fonttype)

        self.chemicals_list = database.keys()
        self.chemicals_list.sort()

        self.name = StringVar()
        self.formula = StringVar()
        self.MW = DoubleVar()
        self.temp = DoubleVar(value=0)
        self.Dw = DoubleVar(value=0)
        self.Ref = StringVar(value=0)
        self.Koc = DoubleVar(value=0)
        self.Kdoc = DoubleVar(value=0)
        self.Kf = DoubleVar(value=0)
        self.N = DoubleVar(value=0)

        self.importedchemicals = {}
        for name in self.chemicals_list:
            self.importedchemicals[name] = ChemicalData(name)
            self.importedchemicals[name].read_database(database[name])

        self.name_width = 10
        self.ref_width = 10

        for chemical_name in self.chemicals_list:
            if (self.tkfont.measure(chemical_name) + 10) > self.name_width:
                self.name_width = self.tkfont.measure(chemical_name) + 10
            for temp in self.importedchemicals[chemical_name].temps:
                if (self.tkfont.measure(
                        self.importedchemicals[chemical_name].Ref[temp]) +
                        10) > self.name_width:
                    self.name_width = self.tkfont.measure(
                        self.importedchemicals[chemical_name].Ref[temp]) + 10

        if self.name_width < 150: self.name_width = 150
        if self.ref_width < 150: self.ref_width = 150

        self.cancelflag = 0

        self.sname = StringVar(self.frame, value='')

    def make_widgets(self):

        self.instructions = Label(
            self.tframe,
            text='Please select the chemical you would like to add       ')

        self.leftcolumn = Label(self.tframe, text=' ', width=2)
        self.checkcolumn = Label(self.tframe, text=' ', width=5)
        self.orinamecolumn = Label(
            self.tframe,
            text=' ',
            width=int(self.name_width * 1.1424219345 / 8) + 1)
        self.tempcolumn = Label(self.tframe, text=' ', width=15)
        self.ref1column = Label(
            self.tframe,
            text=' ',
            width=int(self.ref_width * 1.1424219345 / 8 / 2) + 1)
        self.ref2column = Label(
            self.tframe,
            text=' ',
            width=int(self.ref_width * 1.1424219345 / 8 / 2) + 1)
        self.rightcolumn = Label(self.tframe, text=' ', width=2)

        self.search_label = Label(self.tframe, text='Search:')
        self.search_entry = Entry(self.tframe, textvariable=self.sname)

        self.namelabel = Label(self.tframe, text='Name')
        self.templabel = Label(self.tframe, text='Temperature')
        self.reflabel = Label(self.tframe, text='Reference')

        self.botleftcolumn = Label(self.frame, text=' ', width=2)
        self.botcheckcolumn = Label(self.frame, text=' ', width=5)
        self.botorinamecolumn = Label(
            self.frame,
            text=' ',
            width=int(self.name_width * 1.1424219345 / 8) + 1)
        self.bottempcolumn = Label(self.frame, text=' ', width=15)
        self.botref1column = Label(
            self.frame,
            text=' ',
            width=int(self.ref_width * 1.1424219345 / 8 / 2) + 1)
        self.botref2column = Label(
            self.frame,
            text=' ',
            width=int(self.ref_width * 1.1424219345 / 8 / 2) + 1)
        self.botrightcolumn = Label(self.frame, text=' ', width=2)

        self.importbutton = Button(self.bframe,
                                   text='Import',
                                   command=self.OK,
                                   width=20)
        self.cancelbutton = Button(self.bframe,
                                   text='Cancel',
                                   command=self.cancel,
                                   width=20)

        self.blank1 = Label(self.tframe, text=' ')
        self.blank2 = Label(self.frame, text=' ')
        self.blank3 = Label(self.bframe, text=' ')
        self.blank4 = Label(self.bframe, text=' ')

        #show the widgets on the grid (top to bottom and left to right)

        self.instructions.grid(row=0, columnspan=5, sticky='W', padx=8)

        self.leftcolumn.grid(row=1, column=0, sticky='WE')
        self.checkcolumn.grid(row=1, column=1, sticky='WE')
        self.orinamecolumn.grid(row=1, column=2, sticky='WE')
        self.tempcolumn.grid(row=1, column=3, sticky='WE')
        self.ref1column.grid(row=1, column=4, sticky='WE')
        self.ref2column.grid(row=1, column=5, sticky='WE')
        self.rightcolumn.grid(row=1, column=6, sticky='WE')

        self.search_label.grid(row=2, column=1, sticky='E', padx=4)
        self.search_entry.grid(row=2,
                               column=2,
                               columnspan=4,
                               sticky='WE',
                               padx=4)

        self.blank1.grid(row=3)

        self.namelabel.grid(row=4, column=2, sticky='WE')
        self.templabel.grid(row=4, column=3, sticky='WE')
        self.reflabel.grid(row=4, column=4, columnspan=2, sticky='WE')

        self.botleftcolumn.grid(row=1, column=0, sticky='WE')
        self.botcheckcolumn.grid(row=1, column=1, sticky='WE')
        self.botorinamecolumn.grid(row=1, column=2, sticky='WE')
        self.bottempcolumn.grid(row=1, column=3, sticky='WE')
        self.botref1column.grid(row=1, column=4, sticky='WE')
        self.botref2column.grid(row=1, column=5, sticky='WE')
        self.botrightcolumn.grid(row=1, column=6, sticky='WE')

        self.searchname()

        self.sname.trace('w', self.searchname)

    def searchname(self, event=None, *args):

        row = 2

        for name in self.chemicals_list:
            try:
                self.importedchemicals[name].remove_selectchemicalwidgets()
            except:
                pass

        if self.sname.get() == '':
            for name in self.chemicals_list:
                self.importedchemicals[name].selectchemicalwidgets(
                    self.frame,
                    row=row,
                    master=self.master,
                    namewidth=int(self.name_width * 1.1424219345 / 8) + 1,
                    refwidth=int(self.ref_width * 1.1424219345 / 8) + 1)
                row = row + 1
        else:
            for name in self.chemicals_list:
                if name.lower()[:len(self.sname.get())].count(
                        self.sname.get().lower()) >= 1:
                    self.importedchemicals[name].selectchemicalwidgets(
                        self.frame,
                        row=row,
                        master=self.master,
                        namewidth=int(self.name_width * 1.1424219345 / 8) + 1,
                        refwidth=int(self.ref_width * 1.1424219345 / 8) + 1)
                    row = row + 1
                else:
                    self.importedchemicals[name].check = IntVar(
                        value=self.importedchemicals[name].check)

        self.blank2.grid(row=row)

        row = 2

        self.blank3.grid(row=row)
        row = row + 1
        self.importbutton.grid(row=row, column=0, columnspan=5, pady=1)
        row = row + 1
        self.cancelbutton.grid(row=row, column=0, columnspan=5, pady=1)
        row = row + 1
        self.blank4.grid(row=row)

        self.cancelbutton.bind('<Return>', self.cancel)

        self.focusbutton = self.cancelbutton

    def selectchemicaldata(self, name):

        for othername in self.chemicals_list:
            if othername <> name:
                try:
                    self.importedchemicals[othername].check.set(0)
                except:
                    pass

    def cancelname(self, event=None):

        self.sname.set('')
        self.searchname()

    def OK(self, event=None):

        for name in self.chemicals_list:
            if self.importedchemicals[name].check.get() == 1:

                self.name.set(name)
                self.formula.set(self.importedchemicals[name].formula)
                self.MW.set(self.importedchemicals[name].MW)
                self.temp.set(self.importedchemicals[name].temp.get())
                self.Dw.set(self.importedchemicals[name].Dw[self.temp.get()])
                self.Ref.set(self.importedchemicals[name].Ref[self.temp.get()])
                self.Koc.set(self.importedchemicals[name].Koc[self.temp.get()])
                self.Kdoc.set(
                    self.importedchemicals[name].Kdoc[self.temp.get()])
                self.Kf.set(self.importedchemicals[name].Kf[self.temp.get()])
                self.N.set(self.importedchemicals[name].N[self.temp.get()])

        for name in self.chemicals_list:
            try:
                self.importedchemicals[name].remove_selectchemicalwidgets()
            except:
                pass

        self.frame.quit()

    def cancel(self, event=None):

        self.cancelflag = 1
        self.frame.quit()
示例#35
0
            p_in.close()
            currentCellNumberText.delete(0, 'end')
            currentCellNumberText.insert(INSERT, cellNumber)
        else:
            tkMessageBox.showerror('ERROR', 'No file!')
    except ValueError:
        tkMessageBox.showerror('ERROR', 'Please enter an integer.')


root = Tk()
root.geometry('500x100')
root.resizable(0, 0)

folderPathLabel = Label(master=root, text='Files Directory')

folderPathText = Entry(master=root, width=50)

getDirBtn = Button(root, text="...", command=showDirectory, width=3, padx=10)
cellNumberLabel = Label(master=root, text='Cell Number')
currentCellNumberLabel = Label(master=root, text='Current Cell Number')

cellNumberText = Entry(master=root, width=50)
currentCellNumberText = Entry(master=root, width=50)

saveBtn = Button(root, text="save", command=save, width=3, padx=10)
currentCellNumberBtn = Button(root,
                              text="Current",
                              command=view,
                              width=3,
                              padx=10)
示例#36
0
from Tkinter import Tk, Label, Entry, Button, IntVar

my_app = Tk(className='Bangun Geometri')

L1 = Label(my_app, text='Bangun Geometri', font=('Arial', 24))
L1.grid(row=0, column=0)
L2 = Label(my_app,  text="""Jajar Genjang adalah salah satu bangun geometri dua
            dimensi. Jajar genjang pada umunya memiliki dua pasangan pembentuk,
            yaitu Panjang dan Tinggi. Contoh: Atap, Penghapus bentuk jajar genjang.""")
L2.grid(row=1, column=0)
L3 = Label(my_app, text='Parameter 1 :')
L3.grid(row=2, column=0)
P1 = IntVar()
E1 = Entry(my_app, textvariable=P1)
E1.grid(row=2, column=1)
L4 = Label(my_app, text='Parameter 2 :')
L4.grid(row=3, column=0)
P2 = IntVar()
E2 = Entry(my_app, textvariable=P2)
E2.grid(row=3, column=1)
L5 = Label(my_app, text='')
L5.grid(row=4, column=1)
L6 = Label(my_app, text='Gambar')
L6.grid(row=6, column=0)

def luas():
    'Menghitung luas Jajar genjang'
    _luas = P1.get() * P2.get()
    L5.config(text=_luas)

B = Button(my_app, text='Hitung luas', command=luas)
示例#37
0
class PokerMachine():

    """Implements a video poker machine class."""

    def __init__(self):

        """Instance initialization function."""

        # Set up variables

        self.deck = pcards.Deck()
        self.cardimg = []
        self.hand = None

        self.game_start = True
        self.game_postdeal = False
        self.game_easy = True
        self.game_over = False
        self.gifdir = "./images/"

        self.pot = 100
        self.defaultbet = 5
        self.bet = 5

        self._set_up_gui()

    def button_clicked(self):

        """Event handler for button click.

        Callback method called by tk.

        """

        if self.game_over:
            self._start_new_game()
        elif not self.game_postdeal:
            self._process_bet()
        elif self.game_postdeal:
            self._evaluate_hand()

    def flip(self, event):

        """Event handler which flips a clicked card.

        Callback method called by tk.

        """

        if not self.game_postdeal:
            return

        if event.widget.flipped:
            event.widget.flipped = False
            event.widget.configure(image=event.widget.cardimage)
        else:
            event.widget.flipped = True
            event.widget.configure(image=self.backimg)

    def _start_new_game(self):

        """Returns the game an interface to its starting point."""

        for cardimg in self.cardimg:
            cardimg.configure(image=self.backimg)
            cardimg.flipped = True

        self.game_over = False
        self.game_postdeal = False
        self.pot = 100
        self.defaultbet = 5
        self.bet = 5
        self._update_pot()
        self.bet_amt_fld.configure(state=NORMAL)
        self.bet_str.set(str(self.defaultbet))
        self.button.configure(text="Deal")
        self.status_lbl.configure(text="Click 'Deal' to play.")

    def _process_bet(self):

        """Processes the player's bet and deals a new hand
        if the bet is valid.

        """

        # First check if played made a valid bet,
        # and return with no change in state (other
        # than resetting the bet field) if they did
        # not.

        b_str = self.bet_str.get()

        try:
            self.bet = int(b_str)
        except ValueError:
            self._show_bet_error("Bad bet!", "You must bet a whole number!")
            return

        if self.bet > self.pot:
            self._show_bet_error("Don't be greedy!",
                                 "You don't have that much money!")
            return
        elif self.bet < 1:
            self._show_bet_error("Don't get clever!",
                                 "You must bet a positive whole number!")
            return

        # We have a valid bet, so shuffle the deck
        # and get a new poker hand.

        self.deck.shuffle()
        self.hand = pcards.PokerHand(self.deck)
        self._show_cards()

        # Update game variables and GUI

        self.pot -= self.bet
        self._update_pot()

        self.button.configure(text="Exchange / skip")
        self.status_lbl.configure(text="Choose cards to exchange by " +
                                       "clicking on them.")
        self.bet_amt_fld.configure(state=DISABLED)

        self.game_postdeal = True

    def _evaluate_hand(self):

        """Evalutes a player's hand after any exchanges have
        been made and we have the final hand. Process
        winnings if we have any.

        """

        # Player has flipped their cards if we're here,
        # so figure out which ones they flipped and
        # exchange them and show the new cards.

        xchg_str = ""

        for cardimg in self.cardimg:
            if cardimg.flipped:
                xchg_str += cardimg.pos

        self.hand.exchange(xchg_str)
        self._show_cards()

        # Calculate winnings and show status

        winnings = self.hand.video_winnings(self.bet, easy=self.game_easy)
        win_str = self.hand.show_value() + ". "

        if winnings:
            self.pot += winnings
            win_str += "You won ${0:}!".format(winnings)
            self._update_pot()
        else:
            win_str += "Sorry, no win!"
            if self.pot == 0:
                win_str += " Out of money - game over!"
                self.game_over = True

        self.status_lbl.configure(text=win_str)

        # Update game variables and GUI

        if self.game_over:
            self.button.configure(text="New game")
        else:
            self.button.configure(text="Deal again")
            self.bet_amt_fld.configure(state=NORMAL)

        # Reset the bet amount field with the default bet. Check
        # here to make sure the default bet is not more money that
        # is in the pot, and limit it to that amount if it is.

        self.defaultbet = self.bet if self.bet <= self.pot else self.pot
        self.bet_str.set(str(self.defaultbet))
        self.game_postdeal = False

        # Discard and then drop the current hand

        self.hand.discard()
        self.hand = []

    def _show_bet_error(self, title, message):

        """Shows a message box and resets the bet field
        in response to an invalid bet.

        """

        tkMessageBox.showerror(title, message)
        self.bet = self.defaultbet
        self.bet_str.set(str(self.defaultbet))

    def _update_pot(self):

        """Updates the pot amount label with the current pot."""

        txt_str = "${0:}".format(self.pot)
        self.pot_amt_lbl.configure(text=txt_str)

    def _show_cards(self):

        """Shows the cards in the poker hand on the screen."""

        for cardimg, idx in zip(self.cardimg, self.hand.index_list()):
            cardfile = "{0}{1}.gif".format(self.gifdir, str(idx + 1))
            img = PhotoImage(file=cardfile)
            cardimg.configure(image=img)
            cardimg.cardimage = img
            cardimg.flipped = False

    def _set_up_gui(self):

        """Sets up the Tkinter user interface."""

        # Disable pylint warning for instance attributes defined outside
        # __init__(), since this method is called by __init__()
        #
        # pylint: disable=W0201

        self.root = Tk()
        self.root.title('Video Poker')

        # Set up menubar

        self.menubar = Menu(self.root)

        self.gamemenu = Menu(self.menubar, tearoff=0)
        self.gamemenu.add_command(label="Quit", command=sys.exit)
        self.menubar.add_cascade(label="Game", menu=self.gamemenu)

        self.helpmenu = Menu(self.menubar, tearoff=0)
        self.helpmenu.add_command(label="About", command=self.help_about)
        self.menubar.add_cascade(label="Help", menu=self.helpmenu)

        self.root.config(menu=self.menubar)

        # Set up card images

        self.backimg = PhotoImage(file="{0}b.gif".format(self.gifdir))

        for num in range(5):
            lbl = Label(self.root, image=self.backimg)
            lbl.grid(row=0, column=num, padx=10, pady=10)
            lbl.bind("<Button-1>", self.flip)
            lbl.flipped = True
            lbl.pos = str(num + 1)
            self.cardimg.append(lbl)

        # Set up labels, fields and buttons

        self.pot_lbl = Label(self.root, text="Pot:")
        self.pot_lbl.grid(row=1, column=0,
                          padx=10, pady=2, sticky=W)

        self.pot_amt_lbl = Label(self.root, text="")
        self.pot_amt_lbl.grid(row=1, column=1, columnspan=2,
                              padx=10, pady=2, sticky=W)
        self._update_pot()

        self.bet_lbl = Label(self.root, text="Bet ($):")
        self.bet_lbl.grid(row=2, column=0,
                          padx=10, pady=2, sticky=W)

        self.bet_str = StringVar()
        self.bet_str.set(str(self.defaultbet))

        self.bet_amt_fld = Entry(self.root, textvariable=self.bet_str)
        self.bet_amt_fld.grid(row=2, column=1, columnspan=2,
                              padx=10, pady=2, sticky=W)

        self.button = Button(self.root, text="Deal",
                             command=self.button_clicked)
        self.button.grid(row=1, column=3, rowspan=2, columnspan=2,
                         sticky=W + E + S + N, padx=10)

        self.status_lbl = Label(self.root, bd=1, relief=SUNKEN,
                                text="Welcome to the casino! " +
                                     "Click 'Deal' to play!")
        self.status_lbl.grid(row=3, column=0, columnspan=5,
                             padx=10, pady=10, ipadx=10, ipady=10,
                             sticky=W + E + S + N)

        # Show winnings table

        lbl = Label(self.root, text="Winnings Table", relief=RAISED)
        lbl.grid(row=4, column=1, columnspan=3,
                 pady=15, ipadx=10, ipady=10, sticky=W + E)

        # Two different tables, one for easy mode, one for normal
        # mode, so be prepared to show either one.

        wte = {2500: "Royal Flush", 250: "Straight Flush",
               100: "Four of a Kind", 50: "Full House", 20: "Flush",
               15: "Straight", 4: "Three of a Kind", 3: "Two Pair",
               2: "Jacks or Higher"}
        wtn = {800: "Royal Flush", 50: "Straight Flush", 25: "Four of a Kind",
               9: "Full House", 6: "Flush", 4: "Straight",
               3: "Three of a Kind", 2: "Two Pair", 1: "Jacks or Higher"}
        wtxt = wte if self.game_easy else wtn

        row = 5
        for key in sorted(wtxt.keys(), reverse=True):
            lbl = Label(self.root, text=wtxt[key])
            lbl.grid(row=row, column=1, columnspan=2, sticky=W)
            lbl = Label(self.root, text="{0} : 1".format(key))
            lbl.grid(row=row, column=3, sticky=E)
            row += 1

        lbl = Label(self.root, text="")
        lbl.grid(row=row, column=0, columnspan=5, pady=15)

        # pylint: enable=W0201

    def help_about(self):

        """Shows an 'about' modal dialog.

        Callback method called by tk.

        """

        about_win = Toplevel(self.root)

        # Set up dialog

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

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

        # Show dialog

        about_win.transient(self.root)
        about_win.parent = self.root
        about_win.protocol("WM_DELETE_WINDOW", about_win.destroy)
        about_win.geometry("+{0}+{1}".format(self.root.winfo_rootx() + 50,
                                           self.root.winfo_rooty() + 50))
        about_win.title("About Video Poker")
        about_win.focus_set()
        about_win.grab_set()
        about_win.mainloop()
        about_win.destroy()
示例#38
0
    def _set_up_gui(self):

        """Sets up the Tkinter user interface."""

        # Disable pylint warning for instance attributes defined outside
        # __init__(), since this method is called by __init__()
        #
        # pylint: disable=W0201

        self.root = Tk()
        self.root.title('Video Poker')

        # Set up menubar

        self.menubar = Menu(self.root)

        self.gamemenu = Menu(self.menubar, tearoff=0)
        self.gamemenu.add_command(label="Quit", command=sys.exit)
        self.menubar.add_cascade(label="Game", menu=self.gamemenu)

        self.helpmenu = Menu(self.menubar, tearoff=0)
        self.helpmenu.add_command(label="About", command=self.help_about)
        self.menubar.add_cascade(label="Help", menu=self.helpmenu)

        self.root.config(menu=self.menubar)

        # Set up card images

        self.backimg = PhotoImage(file="{0}b.gif".format(self.gifdir))

        for num in range(5):
            lbl = Label(self.root, image=self.backimg)
            lbl.grid(row=0, column=num, padx=10, pady=10)
            lbl.bind("<Button-1>", self.flip)
            lbl.flipped = True
            lbl.pos = str(num + 1)
            self.cardimg.append(lbl)

        # Set up labels, fields and buttons

        self.pot_lbl = Label(self.root, text="Pot:")
        self.pot_lbl.grid(row=1, column=0,
                          padx=10, pady=2, sticky=W)

        self.pot_amt_lbl = Label(self.root, text="")
        self.pot_amt_lbl.grid(row=1, column=1, columnspan=2,
                              padx=10, pady=2, sticky=W)
        self._update_pot()

        self.bet_lbl = Label(self.root, text="Bet ($):")
        self.bet_lbl.grid(row=2, column=0,
                          padx=10, pady=2, sticky=W)

        self.bet_str = StringVar()
        self.bet_str.set(str(self.defaultbet))

        self.bet_amt_fld = Entry(self.root, textvariable=self.bet_str)
        self.bet_amt_fld.grid(row=2, column=1, columnspan=2,
                              padx=10, pady=2, sticky=W)

        self.button = Button(self.root, text="Deal",
                             command=self.button_clicked)
        self.button.grid(row=1, column=3, rowspan=2, columnspan=2,
                         sticky=W + E + S + N, padx=10)

        self.status_lbl = Label(self.root, bd=1, relief=SUNKEN,
                                text="Welcome to the casino! " +
                                     "Click 'Deal' to play!")
        self.status_lbl.grid(row=3, column=0, columnspan=5,
                             padx=10, pady=10, ipadx=10, ipady=10,
                             sticky=W + E + S + N)

        # Show winnings table

        lbl = Label(self.root, text="Winnings Table", relief=RAISED)
        lbl.grid(row=4, column=1, columnspan=3,
                 pady=15, ipadx=10, ipady=10, sticky=W + E)

        # Two different tables, one for easy mode, one for normal
        # mode, so be prepared to show either one.

        wte = {2500: "Royal Flush", 250: "Straight Flush",
               100: "Four of a Kind", 50: "Full House", 20: "Flush",
               15: "Straight", 4: "Three of a Kind", 3: "Two Pair",
               2: "Jacks or Higher"}
        wtn = {800: "Royal Flush", 50: "Straight Flush", 25: "Four of a Kind",
               9: "Full House", 6: "Flush", 4: "Straight",
               3: "Three of a Kind", 2: "Two Pair", 1: "Jacks or Higher"}
        wtxt = wte if self.game_easy else wtn

        row = 5
        for key in sorted(wtxt.keys(), reverse=True):
            lbl = Label(self.root, text=wtxt[key])
            lbl.grid(row=row, column=1, columnspan=2, sticky=W)
            lbl = Label(self.root, text="{0} : 1".format(key))
            lbl.grid(row=row, column=3, sticky=E)
            row += 1

        lbl = Label(self.root, text="")
        lbl.grid(row=row, column=0, columnspan=5, pady=15)
示例#39
0
    def create_player(self):
        player = Frame(self.root)
        player.pack(fill=X, expand=1)
        # left
        left_frame = Frame(player)
        left_frame.pack(side=LEFT)
        left_team_name = Entry(left_frame, bg='pink', fg='black')
        left_team_name.insert(0, 'A队')
        left_team_name.pack()
        for i in range(1, 7):
            e = Entry(left_frame, bg='red', fg='white')
            name = 'Player' + str(i)
            e.insert(0, name)
            e.pack()
        # right
        right_frame = Frame(player)
        right_frame.pack(side=RIGHT)
        right_team_name = Entry(right_frame, bg='lightBlue', fg='black')
        right_team_name.insert(0, 'B队')
        right_team_name.pack()
        for i in range(7, 13):
            e = Entry(right_frame, bg='blue', fg='white')
            name = 'Player' + str(i)
            e.insert(0, name)
            e.pack()

        self.left_frame = left_frame
        self.right_frame = right_frame
示例#40
0
# form.hidden_input["hidden_var1"] = "value1"
# form.hidden_input["hidden_var2"] = "value2"

Label(form,
      height=1,
      font=('arial', 12, 'bold'),
      text="Question:",
      bg="#99ccff",
      fg='blue4',
      bd=20,
      anchor='w').grid(row=1, column=0, sticky=E, pady=(0, 0))

#function to show and print question
entry = Entry(form,
              font=('arial', 10, 'bold'),
              width=120,
              bd=13,
              bg="#99ccff",
              fg="#012b74")
entry.fieldname = "Question"
entry.grid(row=1, column=1, sticky=E + W)
entry.delete(0, END)
str3 = generateQuestion()
entry.insert(0, (str3))

Label(form,
      font=('arial', 12, 'bold'),
      text="Answer write here:",
      bg="#99ccff",
      fg="#012b74",
      bd=10,
      anchor='w').grid(row=5, column=0, sticky=E, pady=(8, 2))
示例#41
0
    def make_widgets(self):
        """Make the widgets for the window."""

        self.bgcolor = self.frame.cget('bg')
        self.instructions = Label(
            self.tframe,
            text=
            ' Please provide the following chemical properties:                    '
        )

        self.blankcolumn = Label(self.frame, text=' ', width=2)
        self.namecolumn = Label(self.frame, text=' ', width=20)
        self.MWcolumn = Label(self.frame, text=' ', width=12)
        self.tempcolumn = Label(self.frame, text=' ', width=10)
        self.Dwcolumn = Label(self.frame, text=' ', width=18)
        self.Koccolumn = Label(self.frame, text=' ', width=18)
        self.Kdoccolumn = Label(self.frame, text=' ', width=18)
        self.Refcolumn = Label(self.frame, text=' ', width=20)
        self.Rightcolumn = Label(self.frame, text=' ', width=2)

        self.namelabel = Label(self.frame, text='Chemical name')
        self.MWlabel = Label(self.frame, text='Molecular\n weight')
        self.templabel = Label(self.frame, text='Temperature')
        self.Dwlabel = Label(self.frame,
                             text='Molecular diffusivity\n in water')
        self.Koclabel = Label(self.frame,
                              text='Organic carbon\n partition coefficient')
        self.Kdoclabel = Label(
            self.frame,
            text='Dissolved organic carbon\n partition coefficient')
        self.Reflabel = Label(self.frame, text='Reference')

        self.tempunits = Label(self.frame, text=unichr(176) + 'C')
        self.Dwunits = Label(self.frame, text=self.diffunit)
        self.Kocunits = Label(self.frame, text='log(L/kg)')
        self.Kdocunits = Label(self.frame, text='log(L/kg)')

        self.importbutton = Button(self.frame,
                                   text='From Database',
                                   width=20,
                                   command=self.importchemical)
        self.okbutton = Button(self.frame,
                               text='OK',
                               width=20,
                               command=self.OK)
        self.cancelbutton = Button(self.frame,
                                   text='Cancel',
                                   width=20,
                                   command=self.Cancel)
        self.blank1 = Label(self.frame, text=' ')
        self.blank2 = Label(self.frame, text=' ')

        #show the widgets on the grid
        self.instructions.grid(row=0,
                               column=0,
                               columnspan=6,
                               padx=8,
                               sticky='W')

        self.blankcolumn.grid(row=1, column=0, sticky='WE', padx=1, pady=1)
        self.namecolumn.grid(row=1, column=1, sticky='WE', padx=1, pady=1)
        self.MWcolumn.grid(row=1, column=2, sticky='WE', padx=1, pady=1)
        self.tempcolumn.grid(row=1, column=3, sticky='WE', padx=1, pady=1)
        self.Dwcolumn.grid(row=1, column=4, sticky='WE', padx=1, pady=1)
        self.Koccolumn.grid(row=1, column=5, sticky='WE', padx=1, pady=1)
        self.Kdoccolumn.grid(row=1, column=6, sticky='WE', padx=1, pady=1)
        self.Refcolumn.grid(row=1, column=7, sticky='WE', padx=1, pady=1)
        self.Rightcolumn.grid(row=1, column=8, sticky='WE', padx=1, pady=1)

        self.namelabel.grid(row=2, column=1, sticky='WE', padx=1, pady=1)
        self.MWlabel.grid(row=2, column=2, sticky='WE', padx=1, pady=1)
        self.templabel.grid(row=2, column=3, sticky='WE', padx=1, pady=1)
        self.Dwlabel.grid(row=2, column=4, sticky='WE', padx=1, pady=1)
        self.Koclabel.grid(row=2, column=5, sticky='WE', padx=1, pady=1)
        self.Kdoclabel.grid(row=2, column=6, sticky='WE', padx=1, pady=1)
        self.Reflabel.grid(row=2, column=7, sticky='WE', padx=1, pady=1)

        self.tempunits.grid(row=3, column=3, sticky='WE', padx=1, pady=1)
        self.Dwunits.grid(row=3, column=4, sticky='WE', padx=1, pady=1)
        self.Kocunits.grid(row=3, column=5, sticky='WE', padx=1, pady=1)
        self.Kdocunits.grid(row=3, column=6, sticky='WE', padx=1, pady=1)

        if self.soluableflag == 1:
            if self.editflag == 0:
                self.namewidget = Entry(self.frame,
                                        width=18,
                                        justify='center',
                                        textvariable=self.name)
                self.tempwidget = Entry(self.frame,
                                        width=10,
                                        justify='center',
                                        textvariable=self.temp)
            else:
                self.namewidget = Label(self.frame,
                                        width=18,
                                        justify='center',
                                        textvariable=self.name)
                self.tempwidget = Label(self.frame,
                                        width=10,
                                        justify='center',
                                        textvariable=self.temp)

            self.Dwwidget = Entry(self.frame,
                                  width=16,
                                  justify='center',
                                  textvariable=self.Dw)
            self.MWwidget = Entry(self.frame,
                                  width=10,
                                  justify='center',
                                  textvariable=self.MW)
            self.Kocwidget = Entry(self.frame,
                                   width=16,
                                   justify='center',
                                   textvariable=self.Koc)
            self.Kdocwidget = Entry(self.frame,
                                    width=16,
                                    justify='center',
                                    textvariable=self.Kdoc)
            self.Refwidget = Entry(self.frame,
                                   width=18,
                                   justify='center',
                                   textvariable=self.Ref)

            self.namewidget.grid(row=4, column=1, padx=2, pady=1)
            self.MWwidget.grid(row=4, column=2, padx=2, pady=1)
            self.tempwidget.grid(row=4, column=3, padx=2, pady=1)
            self.Dwwidget.grid(row=4, column=4, padx=2, pady=1)
            self.Kocwidget.grid(row=4, column=5, padx=2, pady=1)
            self.Kdocwidget.grid(row=4, column=6, padx=2, pady=1)
            self.Refwidget.grid(row=4, column=7, padx=2, pady=1)

        else:
            self.namewidget = Entry(self.frame,
                                    width=18,
                                    justify='center',
                                    textvariable=self.name)
            self.Dwwidget = Label(self.frame,
                                  width=16,
                                  justify='center',
                                  text='Not applicable')
            self.Kocwidget = Label(self.frame,
                                   width=16,
                                   justify='center',
                                   text='Not applicable')
            self.Kdocwidget = Label(self.frame,
                                    width=16,
                                    justify='center',
                                    text='Not applicable')

            self.namewidget.grid(row=4, column=1, padx=2, pady=1)
            self.Dwwidget.grid(row=4, column=3, padx=2, pady=1)
            self.Kocwidget.grid(row=4, column=4, padx=2, pady=1)
            self.Kdocwidget.grid(row=4, column=5, padx=2, pady=1)

        self.blank1.grid(row=5)
        if self.editflag == 0: self.importbutton.grid(row=6, columnspan=11)
        self.okbutton.grid(row=7, columnspan=11)
        self.cancelbutton.grid(row=8, columnspan=11)
        self.blank2.grid(row=9)
        self.okbutton.bind('<Return>', self.OK)
        self.focusbutton = self.okbutton

        if int((self.tkfont.measure(self.Ref.get()) + 10) * 1.1424219345 /
               8) + 1 > 18:
            self.Refwidget.config(
                width=int((self.tkfont.measure(self.Ref.get()) + 10) *
                          1.1424219345 / 8) + 3)
        if int((self.tkfont.measure(self.name.get()) + 10) * 1.1424219345 /
               8) + 1 > 18:
            self.namewidget.config(
                width=int((self.tkfont.measure(self.name.get()) + 10) *
                          1.1424219345 / 8) + 3)

        self.master.geometry()
        self.master.center()
示例#42
0
    def __init__(self,
                 master,
                 list_of_items=None,
                 autocomplete_function=None,
                 listbox_width=None,
                 listbox_height=7,
                 ignorecase_match=False,
                 startswith_match=True,
                 vscrollbar=True,
                 hscrollbar=True,
                 **kwargs):
        if hasattr(self, "autocomplete_function"):
            if autocomplete_function is not None:
                raise ValueError(
                    "Combobox_Autocomplete subclass has 'autocomplete_function' implemented"
                )
        else:
            if autocomplete_function is not None:
                self.autocomplete_function = autocomplete_function
            else:
                if list_of_items is None:
                    raise ValueError(
                        "If not guiven complete function, list_of_items can't be 'None'"
                    )

                if ignorecase_match:
                    if startswith_match:

                        def matches_function(entry_data, item):
                            return item.startswith(entry_data)
                    else:

                        def matches_function(entry_data, item):
                            return item in entry_data

                    self.autocomplete_function = lambda entry_data: [
                        item for item in self.list_of_items
                        if matches_function(entry_data, item)
                    ]
                else:
                    if startswith_match:

                        def matches_function(escaped_entry_data, item):
                            if re.match(escaped_entry_data, item,
                                        re.IGNORECASE):
                                return True
                            else:
                                return False
                    else:

                        def matches_function(escaped_entry_data, item):
                            if re.search(escaped_entry_data, item,
                                         re.IGNORECASE):
                                return True
                            else:
                                return False

                    def autocomplete_function(entry_data):
                        escaped_entry_data = re.escape(entry_data)
                        return [
                            item for item in self.list_of_items
                            if matches_function(escaped_entry_data, item)
                        ]

                    self.autocomplete_function = autocomplete_function

        self._listbox_height = int(listbox_height)
        self._listbox_width = listbox_width

        self.list_of_items = list_of_items

        self._use_vscrollbar = vscrollbar
        self._use_hscrollbar = hscrollbar

        kwargs.setdefault("background", "white")

        if "textvariable" in kwargs:
            self._entry_var = kwargs["textvariable"]
        else:
            self._entry_var = kwargs["textvariable"] = StringVar()

        Entry.__init__(self, master, **kwargs)

        self._trace_id = self._entry_var.trace('w', self._on_change_entry_var)

        self._listbox = None

        self.bind("<Tab>", self._on_tab)
        self.bind("<Up>", self._previous)
        self.bind("<Down>", self._next)
        self.bind('<Control-n>', self._next)
        self.bind('<Control-p>', self._previous)

        self.bind("<Return>", self._update_entry_from_listbox)
        self.bind("<Escape>", lambda event: self.unpost_listbox())
示例#43
0
    def __init__(self, master):
        '''Init of the GUI'''
        # Frame for progress bar
        self.bottomframe = Frame(master,
                                 highlightbackground="green",
                                 highlightcolor="green",
                                 highlightthickness=1,
                                 width=500,
                                 height=200)
        self.bottomframe.pack(side=BOTTOM)

        # Frame for buttons and entry
        self.leftframe = Frame(master,
                               highlightbackground="blue",
                               highlightcolor="blue",
                               highlightthickness=1,
                               width=400,
                               height=400)
        self.leftframe.pack(side=LEFT)

        # Sub frame  for buttons
        self.leftsubframe_top = Frame(self.leftframe,
                                      highlightbackground="yellow",
                                      highlightcolor="yellow",
                                      highlightthickness=1)
        self.leftsubframe_top.pack(side=TOP)

        # Sub frame for entry
        self.leftsubframe_bot = Frame(self.leftframe,
                                      highlightbackground="purple",
                                      highlightcolor="purple",
                                      highlightthickness=1)
        self.leftsubframe_bot.pack(side=BOTTOM)

        # Frame for wordcloud
        rightframe = Frame(master,
                           highlightbackground="red",
                           highlightcolor="red",
                           highlightthickness=1,
                           width=250,
                           height=250)
        rightframe.pack(side=RIGHT)

        # Browse button
        self.browsebtn = Button(self.leftsubframe_top,
                                text="Browse",
                                command=self.browse)
        self.browsebtn.pack(side=LEFT)

        # Quit button
        self.quitbtn = Button(self.leftsubframe_top,
                              text="Quit",
                              command=self.leftframe.quit)
        self.quitbtn.pack(side=LEFT)

        # Filepath label
        self.pathlabel = Label(self.leftsubframe_bot, text="filename")
        self.pathlabel.pack()

        # Textbox
        self.searchentry = Entry(self.leftsubframe_bot)
        self.searchentry.pack()
        self.searchentry.bind('<Return>', lambda _: self.search())

        # Search button
        self.searchbtn = Button(self.leftsubframe_bot,
                                text="Search",
                                command=self.search)
        self.searchbtn.pack()

        # Word label
        self.wordlabel = Label(self.bottomframe)
        self.wordlabel.pack()

        # Timestamp label
        self.timestamplabel = Label(self.bottomframe)
        self.timestamplabel.pack()

        # estimate label
        self.estimatelabel = Label(self.bottomframe)
        self.estimatelabel.pack()

        # Working Label
        self.workinglabel = Label(self.bottomframe)
        self.workinglabel.pack()

        # Progress Bar
        self.pbar_det = ttk.Progressbar(self.bottomframe,
                                        orient="horizontal",
                                        length=400,
                                        mode="indeterminate")

        # Wordcloud preparation
        self.imagefile = "wordcloudTools/black_background.png"
        self.imagefile = Image.open(self.imagefile)
        self.image1 = self.imagefile.resize((400, 400), Image.ANTIALIAS)
        self.image1 = ImageTk.PhotoImage(self.image1)

        self.panel1 = Label(rightframe, image=self.image1)
        self.display = self.image1
        self.panel1.pack(side=TOP, fill=BOTH, expand=YES)

        # Non GUI initializations
        self.duration = 0
        self.transcription = ""
        self.stemmed = ""
        self.transcription = ""
        self.imagefile2 = 0
        self.image2 = 0
示例#44
0
class ChemicalEditor:
    """Gets the contaminant properties."""
    def __init__(self, master, system, chemical, chemicals, database,
                 editflag):
        """Constructor method.  Defines the parameters to be obtained in this window."""

        self.master = master
        self.fonttype = system.fonttype
        self.version = system.version
        self.superfont = get_superfont(self.fonttype)  #superscript font
        self.frame = Frame(master.frame)
        self.tframe = Frame(master.tframe)
        self.bframe = Frame(master.bframe)
        self.system = system
        self.database = database
        self.top = None  #flag for existence of toplevel#
        self.tkfont = tkFont.Font(font=system.fonttype)

        self.soluableflag = chemical.soluable
        self.editflag = editflag
        self.cancelflag = 0
        self.chemicals = chemicals
        self.diffunit = system.diffunit
        self.diffunits = system.diffunits

        if self.soluableflag == 1:
            self.database = database
            self.chemical = chemical

            self.name = StringVar(value='')
            self.formula = StringVar(value='')
            self.MW = DoubleVar(value=0)
            self.temp = DoubleVar(value=0)
            self.Dw = DoubleVar(value=0)
            self.Ref = StringVar(value='')
            self.Koc = DoubleVar(value=0)
            self.Kdoc = DoubleVar(value=0)
            self.Kf = DoubleVar(value=0)
            self.N = DoubleVar(value=0)

            if editflag == 1:  #Detemine whether the chemical is added or edited

                self.name.set(self.chemical.name)
                self.formula.set(self.chemical.formula)
                self.MW.set(self.chemical.MW)
                self.temp.set(self.chemical.temp)
                self.Dw.set(self.chemical.Dw)
                self.Koc.set(self.chemical.Koc)
                self.Kdoc.set(self.chemical.Kdoc)
                self.Ref.set(self.chemical.Ref)
                self.Kf.set(self.chemical.Kf)
                self.N.set(self.chemical.N)
        else:
            self.name = StringVar(value=' ')
            self.formula = StringVar(value=' ')
            self.MW = DoubleVar(value=100)
            self.temp = DoubleVar(value=0)
            self.Dw = DoubleVar(value=0)
            self.Koc = DoubleVar(value=0)
            self.Kdoc = DoubleVar(value=0)
            self.Kf = DoubleVar(value=0)
            self.N = DoubleVar(value=0)

            if editflag == 1:  #Detemine whether the chemical is added or edited
                self.name.set(chemical.name)

    def make_widgets(self):
        """Make the widgets for the window."""

        self.bgcolor = self.frame.cget('bg')
        self.instructions = Label(
            self.tframe,
            text=
            ' Please provide the following chemical properties:                    '
        )

        self.blankcolumn = Label(self.frame, text=' ', width=2)
        self.namecolumn = Label(self.frame, text=' ', width=20)
        self.MWcolumn = Label(self.frame, text=' ', width=12)
        self.tempcolumn = Label(self.frame, text=' ', width=10)
        self.Dwcolumn = Label(self.frame, text=' ', width=18)
        self.Koccolumn = Label(self.frame, text=' ', width=18)
        self.Kdoccolumn = Label(self.frame, text=' ', width=18)
        self.Refcolumn = Label(self.frame, text=' ', width=20)
        self.Rightcolumn = Label(self.frame, text=' ', width=2)

        self.namelabel = Label(self.frame, text='Chemical name')
        self.MWlabel = Label(self.frame, text='Molecular\n weight')
        self.templabel = Label(self.frame, text='Temperature')
        self.Dwlabel = Label(self.frame,
                             text='Molecular diffusivity\n in water')
        self.Koclabel = Label(self.frame,
                              text='Organic carbon\n partition coefficient')
        self.Kdoclabel = Label(
            self.frame,
            text='Dissolved organic carbon\n partition coefficient')
        self.Reflabel = Label(self.frame, text='Reference')

        self.tempunits = Label(self.frame, text=unichr(176) + 'C')
        self.Dwunits = Label(self.frame, text=self.diffunit)
        self.Kocunits = Label(self.frame, text='log(L/kg)')
        self.Kdocunits = Label(self.frame, text='log(L/kg)')

        self.importbutton = Button(self.frame,
                                   text='From Database',
                                   width=20,
                                   command=self.importchemical)
        self.okbutton = Button(self.frame,
                               text='OK',
                               width=20,
                               command=self.OK)
        self.cancelbutton = Button(self.frame,
                                   text='Cancel',
                                   width=20,
                                   command=self.Cancel)
        self.blank1 = Label(self.frame, text=' ')
        self.blank2 = Label(self.frame, text=' ')

        #show the widgets on the grid
        self.instructions.grid(row=0,
                               column=0,
                               columnspan=6,
                               padx=8,
                               sticky='W')

        self.blankcolumn.grid(row=1, column=0, sticky='WE', padx=1, pady=1)
        self.namecolumn.grid(row=1, column=1, sticky='WE', padx=1, pady=1)
        self.MWcolumn.grid(row=1, column=2, sticky='WE', padx=1, pady=1)
        self.tempcolumn.grid(row=1, column=3, sticky='WE', padx=1, pady=1)
        self.Dwcolumn.grid(row=1, column=4, sticky='WE', padx=1, pady=1)
        self.Koccolumn.grid(row=1, column=5, sticky='WE', padx=1, pady=1)
        self.Kdoccolumn.grid(row=1, column=6, sticky='WE', padx=1, pady=1)
        self.Refcolumn.grid(row=1, column=7, sticky='WE', padx=1, pady=1)
        self.Rightcolumn.grid(row=1, column=8, sticky='WE', padx=1, pady=1)

        self.namelabel.grid(row=2, column=1, sticky='WE', padx=1, pady=1)
        self.MWlabel.grid(row=2, column=2, sticky='WE', padx=1, pady=1)
        self.templabel.grid(row=2, column=3, sticky='WE', padx=1, pady=1)
        self.Dwlabel.grid(row=2, column=4, sticky='WE', padx=1, pady=1)
        self.Koclabel.grid(row=2, column=5, sticky='WE', padx=1, pady=1)
        self.Kdoclabel.grid(row=2, column=6, sticky='WE', padx=1, pady=1)
        self.Reflabel.grid(row=2, column=7, sticky='WE', padx=1, pady=1)

        self.tempunits.grid(row=3, column=3, sticky='WE', padx=1, pady=1)
        self.Dwunits.grid(row=3, column=4, sticky='WE', padx=1, pady=1)
        self.Kocunits.grid(row=3, column=5, sticky='WE', padx=1, pady=1)
        self.Kdocunits.grid(row=3, column=6, sticky='WE', padx=1, pady=1)

        if self.soluableflag == 1:
            if self.editflag == 0:
                self.namewidget = Entry(self.frame,
                                        width=18,
                                        justify='center',
                                        textvariable=self.name)
                self.tempwidget = Entry(self.frame,
                                        width=10,
                                        justify='center',
                                        textvariable=self.temp)
            else:
                self.namewidget = Label(self.frame,
                                        width=18,
                                        justify='center',
                                        textvariable=self.name)
                self.tempwidget = Label(self.frame,
                                        width=10,
                                        justify='center',
                                        textvariable=self.temp)

            self.Dwwidget = Entry(self.frame,
                                  width=16,
                                  justify='center',
                                  textvariable=self.Dw)
            self.MWwidget = Entry(self.frame,
                                  width=10,
                                  justify='center',
                                  textvariable=self.MW)
            self.Kocwidget = Entry(self.frame,
                                   width=16,
                                   justify='center',
                                   textvariable=self.Koc)
            self.Kdocwidget = Entry(self.frame,
                                    width=16,
                                    justify='center',
                                    textvariable=self.Kdoc)
            self.Refwidget = Entry(self.frame,
                                   width=18,
                                   justify='center',
                                   textvariable=self.Ref)

            self.namewidget.grid(row=4, column=1, padx=2, pady=1)
            self.MWwidget.grid(row=4, column=2, padx=2, pady=1)
            self.tempwidget.grid(row=4, column=3, padx=2, pady=1)
            self.Dwwidget.grid(row=4, column=4, padx=2, pady=1)
            self.Kocwidget.grid(row=4, column=5, padx=2, pady=1)
            self.Kdocwidget.grid(row=4, column=6, padx=2, pady=1)
            self.Refwidget.grid(row=4, column=7, padx=2, pady=1)

        else:
            self.namewidget = Entry(self.frame,
                                    width=18,
                                    justify='center',
                                    textvariable=self.name)
            self.Dwwidget = Label(self.frame,
                                  width=16,
                                  justify='center',
                                  text='Not applicable')
            self.Kocwidget = Label(self.frame,
                                   width=16,
                                   justify='center',
                                   text='Not applicable')
            self.Kdocwidget = Label(self.frame,
                                    width=16,
                                    justify='center',
                                    text='Not applicable')

            self.namewidget.grid(row=4, column=1, padx=2, pady=1)
            self.Dwwidget.grid(row=4, column=3, padx=2, pady=1)
            self.Kocwidget.grid(row=4, column=4, padx=2, pady=1)
            self.Kdocwidget.grid(row=4, column=5, padx=2, pady=1)

        self.blank1.grid(row=5)
        if self.editflag == 0: self.importbutton.grid(row=6, columnspan=11)
        self.okbutton.grid(row=7, columnspan=11)
        self.cancelbutton.grid(row=8, columnspan=11)
        self.blank2.grid(row=9)
        self.okbutton.bind('<Return>', self.OK)
        self.focusbutton = self.okbutton

        if int((self.tkfont.measure(self.Ref.get()) + 10) * 1.1424219345 /
               8) + 1 > 18:
            self.Refwidget.config(
                width=int((self.tkfont.measure(self.Ref.get()) + 10) *
                          1.1424219345 / 8) + 3)
        if int((self.tkfont.measure(self.name.get()) + 10) * 1.1424219345 /
               8) + 1 > 18:
            self.namewidget.config(
                width=int((self.tkfont.measure(self.name.get()) + 10) *
                          1.1424219345 / 8) + 3)

        self.master.geometry()
        self.master.center()

    def importchemical(self):

        if self.top is None:

            self.top = CapSimWindow(master=self.master, buttons=2)
            self.top.make_window(
                ChemicalImporter(self.top, self.system, self.database))
            self.top.tk.mainloop()

            if self.top.window.cancelflag == 0:
                self.updatechemical(self.top.window)

            if self.top is not None:
                self.top.destroy()
                self.top = None

        elif self.top is not None:
            tkmb.showerror(
                title=self.system.version,
                message=
                'Please close the existing parameter input window first.')
            self.top.tk.focus()

    def updatechemical(self, window):

        self.name.set(window.name.get())
        self.formula.set(window.formula.get())
        self.MW.set(window.MW.get())
        self.temp.set(window.temp.get())
        self.Koc.set(window.Koc.get())
        self.Kdoc.set(window.Kdoc.get())
        self.Ref.set(window.Ref.get())
        self.Kf.set(window.Kf.get())
        self.N.set(window.N.get())

        if self.diffunit == self.diffunits[0]: self.Dw.set(window.Dw.get())
        elif self.diffunit == self.diffunits[1]:
            Dw = window.Dw.get() * 86400 * 365
            if Dw > 1: self.Dw.set(round(Dw, 2))
            else:
                i = 2
                while Dw / 100 < 0.1**i:
                    i = i + 1
                self.Dw.set(round(Dw, i))

        self.frame.update()

        if int((self.tkfont.measure(self.Ref.get()) + 10) * 1.1424219345 /
               8) + 1 > 20:
            self.Refwidget.config(
                width=int((self.tkfont.measure(self.Ref.get()) + 10) *
                          1.1424219345 / 8) + 3)
        if int((self.tkfont.measure(self.name.get()) + 10) * 1.1424219345 /
               8) + 1 > 20:
            self.namewidget.config(
                width=int((self.tkfont.measure(self.name.get()) + 10) *
                          1.1424219345 / 8) + 3)
        self.master.geometry()
        self.master.center()

    def OK(self, event=None):
        """Finish and move on.  Checks that the number chemicals are less than the total number of chemicals in database."""

        if self.editflag == 0:
            check = [(chemical.name == self.name.get())
                     for chemical in self.chemicals[0:-1]]
        else:
            check = [0]

        if self.master.window.top is not None: self.master.open_toplevel()
        elif sum(check) >= 1: self.chemicals_error()
        elif self.name.get() == '' or self.name.get().count(' ') == len(
                self.name.get()):
            self.name_error()
        elif self.Dw.get() == 0:
            self.Dw_error()
        else:
            self.master.tk.quit()

    def chemicals_error(self):

        tkmb.showerror(title=self.version,
                       message='This chemical has already been selected!')
        self.focusbutton = self.okbutton
        self.master.tk.lift()

    def name_error(self):

        tkmb.showerror(title=self.version,
                       message='Please input the name for the chemical!')
        self.focusbutton = self.okbutton
        self.master.tk.lift()

    def Dw_error(self):

        tkmb.showerror(
            title=self.version,
            message=
            'The diffusivity of the chemical can not be zero, please correct!')
        self.focusbutton = self.okbutton
        self.master.tk.lift()

    def Cancel(self):

        try:
            self.name.set(self.chemical.name)
            self.MW.set(self.chemical.MW.get())
            self.formula.set(self.chemical.formula.get())
            self.temp.set(self.chemical.temp.get())
            self.Dw.set(self.chemical.Dw.get())
            self.Koc.set(self.chemical.Koc.get())
            self.Kdoc.set(self.chemical.Kdoc.get())
            self.Ref.set(self.chemical.Ref.get())
            self.Kf.set(self.chemical.Kf.get())
            self.N.set(self.chemical.N.get())
        except:
            self.cancelflag = 1

        if self.master.window.top is not None: self.master.open_toplevel()
        else: self.master.tk.quit()
示例#45
0
class FrameFormat(object):
    def __init__(self, gui, master, frame):
        self.main_label = Label(frame, text="TIMESAT image viewer")
        self.address_label = Label(
            frame,
            text=
            "D:/-LTH-/-HT 17-/GIT-projekt i Python/Projekt/EXTP40_2017/EXTP40_2017/wa_cl00011.img",
            relief=SUNKEN)
        self.type_label = Label(frame, text="Image file type")
        type_box_value = StringVar()
        self.type_box = ttk.Combobox(frame,
                                     textvariable=type_box_value,
                                     state='readonly')
        self.type_box['values'] = (
            '8-bit unsigned integer',
            '16-bit signed integer',
            '32-bit real',
        )
        self.type_box.current(0)
        self.order_label = Label(frame, text="Byte order")
        order_box_value = StringVar()
        self.order_box = ttk.Combobox(frame,
                                      textvariable=order_box_value,
                                      state='readonly')
        self.order_box['values'] = (
            'Little endian',
            'Big endian',
        )
        self.order_box.current(0)
        self.row_label = Label(frame, text="Nbr of rows")
        self.col_label = Label(frame, text="Nbr of columns")

        self.row_var = IntVar()
        self.col_var = IntVar()

        vcmd = master.register(self.nbr_check)  # we have to wrap the command
        self.row_entry = Entry(frame,
                               validate="key",
                               validatecommand=(vcmd, '%P'),
                               textvariable=self.row_var)
        self.col_entry = Entry(frame,
                               validate="key",
                               validatecommand=(vcmd, '%P'),
                               textvariable=self.col_var)

        self.draw_button = Button(
            frame,
            text="Draw",
            command=lambda: gui.display(self.type_box.get(
            ), self.order_box.get(), self.row_entry.get(), self.col_entry.get(
            )))

        self.main_label.grid(row=0, column=0, sticky='w')
        self.address_label.grid(row=1, column=0)
        self.type_label.grid(row=2, column=0, sticky='w')
        self.type_box.grid(row=2, column=0)
        self.order_label.grid(row=3, column=0, sticky='w')
        self.order_box.grid(row=3, column=0)

        self.row_label.grid(row=4, column=0, sticky='w')
        self.row_entry.grid(row=4, column=0)
        self.col_label.grid(row=5, column=0, sticky='w')
        self.col_entry.grid(row=5, column=0)

        self.draw_button.grid(row=5, column=2, sticky='w')

    #Only numbers in the entries. Might want to use this in min/max entry in FrameScale
    def nbr_check(self, new_text):
        if not new_text:  # the field is being cleared
            return True  # return that the entry is empty
        try:
            self.entered_number = int(new_text)
            return True
        except ValueError:
            return False

    def update_address(self, path, col):
        self.address_label.config(text=path, fg=col)
示例#46
0
    def make_widgets(self):

        self.instructions = Label(
            self.tframe,
            text='Please select the chemical you would like to add       ')

        self.leftcolumn = Label(self.tframe, text=' ', width=2)
        self.checkcolumn = Label(self.tframe, text=' ', width=5)
        self.orinamecolumn = Label(
            self.tframe,
            text=' ',
            width=int(self.name_width * 1.1424219345 / 8) + 1)
        self.tempcolumn = Label(self.tframe, text=' ', width=15)
        self.ref1column = Label(
            self.tframe,
            text=' ',
            width=int(self.ref_width * 1.1424219345 / 8 / 2) + 1)
        self.ref2column = Label(
            self.tframe,
            text=' ',
            width=int(self.ref_width * 1.1424219345 / 8 / 2) + 1)
        self.rightcolumn = Label(self.tframe, text=' ', width=2)

        self.search_label = Label(self.tframe, text='Search:')
        self.search_entry = Entry(self.tframe, textvariable=self.sname)

        self.namelabel = Label(self.tframe, text='Name')
        self.templabel = Label(self.tframe, text='Temperature')
        self.reflabel = Label(self.tframe, text='Reference')

        self.botleftcolumn = Label(self.frame, text=' ', width=2)
        self.botcheckcolumn = Label(self.frame, text=' ', width=5)
        self.botorinamecolumn = Label(
            self.frame,
            text=' ',
            width=int(self.name_width * 1.1424219345 / 8) + 1)
        self.bottempcolumn = Label(self.frame, text=' ', width=15)
        self.botref1column = Label(
            self.frame,
            text=' ',
            width=int(self.ref_width * 1.1424219345 / 8 / 2) + 1)
        self.botref2column = Label(
            self.frame,
            text=' ',
            width=int(self.ref_width * 1.1424219345 / 8 / 2) + 1)
        self.botrightcolumn = Label(self.frame, text=' ', width=2)

        self.importbutton = Button(self.bframe,
                                   text='Import',
                                   command=self.OK,
                                   width=20)
        self.cancelbutton = Button(self.bframe,
                                   text='Cancel',
                                   command=self.cancel,
                                   width=20)

        self.blank1 = Label(self.tframe, text=' ')
        self.blank2 = Label(self.frame, text=' ')
        self.blank3 = Label(self.bframe, text=' ')
        self.blank4 = Label(self.bframe, text=' ')

        #show the widgets on the grid (top to bottom and left to right)

        self.instructions.grid(row=0, columnspan=5, sticky='W', padx=8)

        self.leftcolumn.grid(row=1, column=0, sticky='WE')
        self.checkcolumn.grid(row=1, column=1, sticky='WE')
        self.orinamecolumn.grid(row=1, column=2, sticky='WE')
        self.tempcolumn.grid(row=1, column=3, sticky='WE')
        self.ref1column.grid(row=1, column=4, sticky='WE')
        self.ref2column.grid(row=1, column=5, sticky='WE')
        self.rightcolumn.grid(row=1, column=6, sticky='WE')

        self.search_label.grid(row=2, column=1, sticky='E', padx=4)
        self.search_entry.grid(row=2,
                               column=2,
                               columnspan=4,
                               sticky='WE',
                               padx=4)

        self.blank1.grid(row=3)

        self.namelabel.grid(row=4, column=2, sticky='WE')
        self.templabel.grid(row=4, column=3, sticky='WE')
        self.reflabel.grid(row=4, column=4, columnspan=2, sticky='WE')

        self.botleftcolumn.grid(row=1, column=0, sticky='WE')
        self.botcheckcolumn.grid(row=1, column=1, sticky='WE')
        self.botorinamecolumn.grid(row=1, column=2, sticky='WE')
        self.bottempcolumn.grid(row=1, column=3, sticky='WE')
        self.botref1column.grid(row=1, column=4, sticky='WE')
        self.botref2column.grid(row=1, column=5, sticky='WE')
        self.botrightcolumn.grid(row=1, column=6, sticky='WE')

        self.searchname()

        self.sname.trace('w', self.searchname)
示例#47
0
    def __init__(self, gui, master, frame):
        self.main_label = Label(frame, text="TIMESAT image viewer")
        self.address_label = Label(
            frame,
            text=
            "D:/-LTH-/-HT 17-/GIT-projekt i Python/Projekt/EXTP40_2017/EXTP40_2017/wa_cl00011.img",
            relief=SUNKEN)
        self.type_label = Label(frame, text="Image file type")
        type_box_value = StringVar()
        self.type_box = ttk.Combobox(frame,
                                     textvariable=type_box_value,
                                     state='readonly')
        self.type_box['values'] = (
            '8-bit unsigned integer',
            '16-bit signed integer',
            '32-bit real',
        )
        self.type_box.current(0)
        self.order_label = Label(frame, text="Byte order")
        order_box_value = StringVar()
        self.order_box = ttk.Combobox(frame,
                                      textvariable=order_box_value,
                                      state='readonly')
        self.order_box['values'] = (
            'Little endian',
            'Big endian',
        )
        self.order_box.current(0)
        self.row_label = Label(frame, text="Nbr of rows")
        self.col_label = Label(frame, text="Nbr of columns")

        self.row_var = IntVar()
        self.col_var = IntVar()

        vcmd = master.register(self.nbr_check)  # we have to wrap the command
        self.row_entry = Entry(frame,
                               validate="key",
                               validatecommand=(vcmd, '%P'),
                               textvariable=self.row_var)
        self.col_entry = Entry(frame,
                               validate="key",
                               validatecommand=(vcmd, '%P'),
                               textvariable=self.col_var)

        self.draw_button = Button(
            frame,
            text="Draw",
            command=lambda: gui.display(self.type_box.get(
            ), self.order_box.get(), self.row_entry.get(), self.col_entry.get(
            )))

        self.main_label.grid(row=0, column=0, sticky='w')
        self.address_label.grid(row=1, column=0)
        self.type_label.grid(row=2, column=0, sticky='w')
        self.type_box.grid(row=2, column=0)
        self.order_label.grid(row=3, column=0, sticky='w')
        self.order_box.grid(row=3, column=0)

        self.row_label.grid(row=4, column=0, sticky='w')
        self.row_entry.grid(row=4, column=0)
        self.col_label.grid(row=5, column=0, sticky='w')
        self.col_entry.grid(row=5, column=0)

        self.draw_button.grid(row=5, column=2, sticky='w')
示例#48
0
    def __init__(self, root, modifstruct, param_visu, mess):
        """!Creation de l'interface pour le calcul de condensation de la mesure

        """
        Frame.__init__(self, root, relief='sunken', borderwidth=1)
        self.root = root
        self.modif_struct = modifstruct
        self.param_visu = param_visu
        self.mess = mess
        self.columnconfigure(0, weight=1)
        self.columnconfigure(1, weight=1)
        self.columnconfigure(2, weight=1)
        self.rowconfigure(1, weight=1)
        self.term = []

        objects = self.root.objects
        # Déclaration des variables Tk
        self.var_resu_exp = StringVar()
        self.condens_meth = StringVar()
        self.var_modl_sup = StringVar()
        self.var_grno_capt = StringVar()
        self.var_grno_intf = StringVar()
        self.var_raid_name = StringVar()
        self.var_modlx = StringVar()
        self.sumail_name = StringVar()

        self.param_mode_iter_simult_lmme = None
        self.param_dlg = None

        # -----------------------------------------------------------------
        # Titre
        #
        Label(self, text="Choix de la base d'expansion", font=self.root.font2
              ).grid(row=0, column=0, columnspan=3, sticky="ew")

        # -----------------------------------------------------------------
        # Definition du modele support
        f = Frame(self)
        f.grid(row=1, column=0, sticky='nsew', padx=60)
        f.columnconfigure(0, weight=3)

        # menu de selection des modes identifies
        Label(f, text="Modes experimentaux").grid(row=0, column=0, sticky='w')
        self.menu_resu_exp = MyMenu(f, objects.get_mode_meca_name(),
                                    self.var_resu_exp, self.refresh_list_exp)
        self.menu_resu_exp.grid(row=0, column=1, sticky='ew')

        # menu de selection du modele support
        Label(f, text="Modele support").grid(row=1, column=0, sticky='w')
        self.menu_modl_sup = MyMenu(f, objects.get_model_name(),
                                    self.var_modl_sup, self.modele_support_changed)
        self.menu_modl_sup.grid(row=1, column=1, sticky='ew')

        # menu de selection de la matrice de raideur assemblee du modele
        # support
        Label(f, text="Matrice raideur (support)",
              justify='left').grid(row=2, column=0, sticky='w')
        self.menu_raid_name = MyMenu(f, objects.get_matr_name(),
                                     self.var_raid_name,
                                     self.mat_raideur_changed)
        self.menu_raid_name.grid(row=2, column=1, sticky='ew')

        Label(f, text="Methode (base expansion)").grid(
            row=3, column=0, sticky='w')

        self.dic_condens_meth = {
            "ES": "Expansion statique",
            "LMME": "Expansion statique projetee",
        }

        self.menu_condens_meth = MyMenu(f, self.dic_condens_meth.keys(),
                                        self.condens_meth,
                                        self.condens_changed)
        self.menu_condens_meth.grid(row=3, column=1, sticky='ew')
        self.condens_meth.set("ES")

        # menu selection du modele modification
        Label(f, text="Modele modification").grid(row=4, column=0, sticky='w')
        self.menu_modlx = MyMenu(f, objects.get_model_name(),
                                 self.var_modlx, self.modele_modif_changed)
        self.menu_modlx.grid(row=4, column=1, sticky='ew')

        # menu de selection du groupe de noeuds capteur
        self.capteur = SelectionNoeuds(f, "Noeuds et DDL capteur",
                                       bg='#90a090', command=self.capteur_changed)
        self.capteur.grid(row=5, column=0, columnspan=2, pady=3, sticky='ew')

        # menu de selection du groupe de noeuds interface
        self.iface = SelectionNoeuds(f, "Noeuds et DDL interface",
                                     bg='#9090a0', command=self.iface_changed)
        self.iface.grid(row=6, column=0, columnspan=2, pady=3, sticky='ew')

        Label(f, text="Nom de la super maille : ").grid(
            row=7, column=0, sticky='w')
        Entry(f, textvariable=self.sumail_name).grid(row=7, column=1)
        self.sumail_name.set("SUMAIL")

        Button(f, text="Valider", command=self.anything_changed).grid(row=8,
                                                                      column=1,
                                                                      sticky='e')

        # -----------------------------------------------------------------
        # menu de selection des modes identifies experimentalement
        f = Frame(self)
        f.grid(row=1, column=1, sticky='nsew')
        f.rowconfigure(0, weight=1)
        self.liste_exp = ModeFreqList(f, "Modes du modele experimental")
        self.liste_exp.grid(row=0, column=0, columnspan=2, sticky='nsew')
        Button(f, text="Voir", command=self.view_model_exp).grid(row=1,
                                                                 column=0,
                                                                 columnspan=2)

        # -----------------------------------------------------------------
        # menu de selection de la methode pour
        # le calcul de la base d'expansion
        f = Frame(self)
        f.grid(row=1, column=2, sticky='nsew')
        f.rowconfigure(0, weight=1)
        self.liste_sup = ModeFreqList(f, "Base d'expansion")
        self.liste_sup.grid(row=0, column=0, sticky='snew')

        Button(f, text="Voir", command=self.view_expansion).grid(
            row=1, column=0)

        self.reglage_lmme_visible = IntVar()
        self.button_reglage_lmme = Checkbutton(f, text="Reglages LMME",
                                               variable=self.reglage_lmme_visible,
                                               command=self.show_param_dialog,
                                               state='disabled', indicatoron=0)

        self.reglage_lmme_visible.set(0)
        self.button_reglage_lmme.grid(row=1, column=1)
        self.configure_param_lmme_dialog()
示例#49
0
    try:
        f = open(fn, 'U')
    except IOError, e:
        from cStringIO import StringIO
        f = StringIO(DEMO)
        en.delete(0, 'end')
        if fn.lower() == 'demo':
            en.insert(0, fn)
        else:
            import os
            en.insert(0, r"DEMO (can't open %s: %s)" % (os.path.join(os.getcwd(), fn), str(e)))
        en.update_idletasks()
    txt2ppt(line.rstrip() for line in f)
    f.close()


if __name__ == '__main__':
    tk = Tk()
    lb = Label(tk, text='Enter file [or "DEMO"]:')
    lb.pack()
    en = Entry(tk)
    en.bind('<Return>', _start)
    en.pack()
    en.focus_set()
    quit = Button(tk, text="QUIT", command=tk.quit, fg='white', bg='red')
    quit.pack(fill='x', expand=True)
    tk.mainloop()



示例#50
0
        else:
            chord.grid_remove()


if __name__ == '__main__':
    from Tkinter import Entry, Button, Text

    root = Tk()

    # create the Accordion
    acc = Accordion(root)

    # first chord
    first_chord = Chord(acc, title='First Chord', bg='white')
    Label(first_chord, text='hello world', bg='white').pack()

    # second chord
    second_chord = Chord(acc, title='Second Chord', bg='white')
    Entry(second_chord).pack()
    Button(second_chord, text='Button').pack()

    # third chord
    third_chord = Chord(acc, title='Third Chord', bg='white')
    Text(third_chord).pack()

    # append list of chords to Accordion instance
    acc.append_chords([first_chord, second_chord, third_chord])
    acc.pack(fill='both', expand=1)

    root.mainloop()
示例#51
0
class HeadUnit_Window:
    def __init__(self, master):
        self.master = master
        self.frame = Frame(self.master)

        # Setup GUI buttons and labels###

        label = Label(self.frame, height=1, width=10, text="UP button")
        label.grid(column=0, row=0, sticky="EW")

        self.UPVariable = StringVar()
        self.entry = Entry(self.frame, textvariable=self.UPVariable)
        self.entry.grid(column=1, row=0, sticky="EW")
        self.UPVariable.set(UP)

        label = Label(self.frame, height=1, width=10, text="DOWN button")
        label.grid(column=0, row=1, sticky="EW")

        self.DOWNVariable = StringVar()
        self.entry = Entry(self.frame, textvariable=self.DOWNVariable)
        self.entry.grid(column=1, row=1, sticky="EW")
        self.DOWNVariable.set(DOWN)

        label = Label(self.frame, height=1, width=10, text="ENTER button")
        label.grid(column=0, row=2, sticky="EW")

        self.ENTERVariable = StringVar()
        self.entry = Entry(self.frame, textvariable=self.ENTERVariable)
        self.entry.grid(column=1, row=2, sticky="EW")
        self.ENTERVariable.set(ENTER)

        label = Label(self.frame, height=1, width=10, text="CANCEL button")
        label.grid(column=0, row=3, sticky="EW")

        self.CANCELVariable = StringVar()
        self.entry = Entry(self.frame, textvariable=self.CANCELVariable)
        self.entry.grid(column=1, row=3, sticky="EW")
        self.CANCELVariable.set(CANCEL)

        self.buttonHeadUnit = Button(
            self.frame,
            height=1,
            width=20,
            text=u"Update Head Unit",
            command=self.setHEADUNITbutton,
        )
        self.buttonHeadUnit.grid(column=0, row=4)

        self.buttonNeedHelp = Button(
            self.frame,
            height=1,
            width=20,
            text=u"Need Help?",
            command=self.NEEDHELPbutton,
        )
        self.buttonNeedHelp.grid(column=1, row=4)

        self.frame.pack()

    def setHEADUNITbutton(self):
        global UP, DOWN, ENTER, CANCEL

        UP = self.UPVariable.get()
        DOWN = self.DOWNVariable.get()
        ENTER = self.ENTERVariable.get()
        CANCEL = self.CANCELVariable.get()

        f = open(filename, "w+")
        f.write(
            "This file contains information regarding Head Unit buttons and Zwift keyboard shortcuts mapping \r\n"
        )
        f.write(UP + "\n")
        f.write(DOWN + "\n")
        f.write(ENTER + "\n")
        f.write(CANCEL + "\n")
        f.close()

        self.master.destroy()

    def NEEDHELPbutton(self):
        os.startfile("Zwift_shortcuts.txt")
示例#52
0
 def __init__(self):
     self.cmp = Entry()
示例#53
0
class Dialog2():
    # from Tkinter import Tk, Label, Entry, END, Button, W, mainloop

    def __init__(self, master):
        from Tkinter import Tk, Label, Entry, END, Button, E, mainloop
        import sys

        self.master = master
        master.title('Please enter values for calculation')

        self.label_cross = Label(master, text='crosssection:').grid(row=0)
        Label(master, text='density:').grid(row=1)
        Label(master, text='perimeter:').grid(row=2)
        Label(master, text='length:').grid(row=3)
        Label(master, text='ambient temperature:').grid(row=4)

        self.e1 = Entry(master)
        self.e2 = Entry(master)
        self.e3 = Entry(master)
        self.e4 = Entry(master)
        self.e5 = Entry(master)

        # default values:
        crosssection_initial = 10
        density_initial = 10000
        perimeter_initial = 22
        length_initial = 10
        ambient_temperature_initial = 296.15

        self.e1.insert(END, crosssection_initial)
        self.e2.insert(END, density_initial)
        self.e3.insert(END, perimeter_initial)
        self.e4.insert(END, length_initial)
        self.e5.insert(END, ambient_temperature_initial)

        self.e1.grid(row=0, column=1)
        self.e2.grid(row=1, column=1)
        self.e3.grid(row=2, column=1)
        self.e4.grid(row=3, column=1)
        self.e5.grid(row=4, column=1)

        def combine_funcs(*funcs):
            def combined_func(*args, **kwargs):
                for f in funcs:
                    f(*args, **kwargs)

            return combined_func

        # self.show_button = Button(master, text='Show',
        # command=self.show_entry_fields) \
        # .grid(row=5, column=0, sticky=W, pady=4)
        self.close_button = Button(master,
                                   text='OK',
                                   command=combine_funcs(
                                       self.show_entry_fields, master.destroy))
        self.close_button.grid(row=5, column=0, sticky=E, pady=4)
        self.quit_button = Button(master, text='Quit', command=sys.exit)
        self.quit_button.grid(row=5, column=1, sticky=E, pady=4)
        # self.close_button.bind('<Return>', self.close_button)

    def show_entry_fields(self):

        # default values:
        crosssection_initial = 10
        density_initial = 10000
        perimeter_initial = 22
        length_initial = 10
        ambient_temperature_initial = 296.15

        global crosssection, density, perimeter, length, ambient_temperature
        try:
            crosssection = float(self.e1.get())
        except ValueError:
            crosssection = crosssection_initial
        try:
            density = float(self.e2.get())
        except ValueError:
            density = density_initial
        try:
            perimeter = float(self.e3.get())
        except ValueError:
            perimeter = perimeter_initial
        try:
            length = float(self.e4.get())
        except ValueError:
            length = length_initial
        try:
            ambient_temperature = float(self.e5.get())
        except ValueError:
            ambient_temperature = ambient_temperature_initial
        # print('crosssection: \t\t\t', crosssection, 'mm^2', '\n', \
        #     'density: \t\t\t\t', density, 'g/mm^2', '\n', \
        #     'perimeter: \t\t\t', perimeter, 'mm', '\n', \
        #     'length: \t\t\t', length, 'mm', '\n', \
        #     'ambient temperature: \t', ambient_temperature, 'K')
        # print([crosssection, density, perimeter,
        #        length, ambient_temperature])
        return [crosssection, density, perimeter, length, ambient_temperature]
示例#54
0
文件: gui.py 项目: omrikiantman/dmex4
class Gui:
    def __init__(self, master, head_title):
        self.master = master
        self.head_title = head_title
        master.title(head_title)

        # params definition
        self.n_clusters = 4
        self.n_init = 10
        self.file_path = 'C:/'
        self.is_pre_processed = False
        self.processor = None
        self.cluster = None

        # Tkinter gui

        self.file_path_text = StringVar(value=self.file_path)
        self.file_path_label = Label(master, text='Data path:')
        self.file_path_entry = Entry(master, textvariable=self.file_path_text, width=50)
        self.browse_button = Button(master, text='Browse', command=self.browse)

        self.n_clusters_text = StringVar(value=self.n_clusters)
        self.n_clusters_label = Label(master, text='Num of clusters k:')
        self.n_clusters_entry = Entry(master, textvariable=self.n_clusters_text)

        self.n_init_text = StringVar(value=self.n_init)
        self.n_init_label = Label(master, text='Num of runs:')
        self.n_init_entry = Entry(master, textvariable=self.n_init_text)

        self.pre_process_button = Button(master, text='Pre-process', command=self.pre_process)
        self.build_model_button = Button(master, text='Cluster', command=self.build_model)

        self.scatter_label = Label(self.master)
        self.horopleth_label = Label(master)
        # LAYOUT

        self.file_path_label.grid(row=0, column=0, sticky=W)
        self.file_path_entry.grid(row=0, column=1, columnspan=2)
        self.browse_button.grid(row=0, column=2, sticky=E)

        self.n_clusters_label.grid(row=1, column=0, sticky=W)
        self.n_clusters_entry.grid(row=1, column=1, columnspan=2, sticky=W+E)

        self.n_init_label.grid(row=2, column=0, sticky=W)
        self.n_init_entry.grid(row=2, column=1, columnspan=2, sticky=W+E)

        self.pre_process_button.grid(row=3, column=1, sticky=W)
        self.build_model_button.grid(row=4, column=1, sticky=W)

        self.scatter_label.grid(row=5, column=0, sticky=W)
        self.horopleth_label.grid(row=5, column=1, sticky=E)

    def browse(self):
        # browse method for choosing the data file
        path = tkFileDialog.askopenfilename()
        if path is None or path == '':
            return

        self.file_path = path
        self.file_path_text.set(self.file_path)

    def pre_process(self):
        # pre process the data to fit into the algorithm
        if self.processor is not None:
            # if we already ran this, ask the user if he wants to run it again
            result = tkMessageBox.askquestion(
                message="pre-processing has already been made.\nare you sure you want to run it again?'",
                icon='warning', title=self.head_title)
            if result != 'yes':
                return
        self.processor = None
        self.is_pre_processed = False
        try:
            # verify the file can be pre-processed
            self.file_path = self.file_path_text.get()
            processor = PreProcess(self.file_path)
            if processor.verifications() is False:
                tkMessageBox.showerror(title=self.head_title, message=processor.error_message)
                return

            # process the data
            processor.pre_process()
            tkMessageBox.showinfo(title=self.head_title, message='Preprocessing completed successfully')
            self.processor = processor
            self.is_pre_processed = True
        except Exception as err:
            template = "An exception of type {0} occurred. Arguments:{1}"
            message = template.format(type(err).__name__, err)
            print_exc(err, file=stdout)
            tkMessageBox.showerror(title=self.head_title, message=message)

    def build_model(self):
        # build the kmeans model
        if not self.is_pre_processed:
            tkMessageBox.showerror(title=self.head_title, message="pre processing is not validated yet")
            return

        if self.cluster is not None:
            # if we already ran the clustering, verify if we really want to run it again
            result = tkMessageBox.askquestion(
                message="clustering has already been made.\nare you sure you want to run it again?",
                icon='warning', title=self.head_title)
            if result != 'yes':
                return
        self.cluster = None
        try:
            # create the kmeans model
            self.n_clusters = self.n_clusters_text.get()
            self.n_init = self.n_init_text.get()
            model = BuildCluster(self.n_clusters, self.n_init, self.processor.df)
            if model.verifications() is False:
                tkMessageBox.showerror(title=self.head_title, message=model.error_message)
                return

            model.build_cluster()
            self.cluster = model
            # draw the graphs in the gui
            self.draw_graphs()
            tkMessageBox.showinfo(title=self.head_title, message='Clustering Finished successfully!')
        except Exception as err:
            template = "An exception of type {0} occurred. Arguments:{1}"
            message = template.format(type(err).__name__, err)
            print_exc(err, file=stdout)
            tkMessageBox.showerror(title=self.head_title, message=message)

    def draw_graphs(self):
        # draw scatter graph using matPlotLib and plotly
        self.draw_scatter()
        self.draw_horopleth()

    def draw_scatter(self):
        # Draw a scatter plot of Generosity vs social support
        df = self.cluster.df
        fig_path = 'scatter.png'
        plt.scatter(x=df['Generosity'], y=df['Social support'], c=df['cluster'], alpha=0.5)
        plt.xlabel('Generosity')
        plt.ylabel('Social support')
        plt.title("Scatter of Generosity vs Social Support, colored by clusters")
        plt.savefig(fig_path)
        # convert from png to gif
        convert_png_to_gif(fig_path)
        # display in GUI
        photo = PhotoImage(file=fig_path.replace('png', 'gif'))
        self.scatter_label.configure(image=photo, width='400px', height='400px')
        self.scatter_label.image = photo

    def draw_horopleth(self):
        # Draw a horopleth of the country clusters
        df = self.cluster.df
        py.sign_in('omrikipiki', 'VcDvTak2bEIiyOfiaxMj')
        data = [dict(
            type='choropleth',
            locations=df['country'],
            z=df['cluster'],
            text=df['country'],
            locationmode='country names',
            colorscale=[[0, "rgb(5, 10, 172)"], [0.35, "rgb(40, 60, 190)"], [0.5, "rgb(70, 100, 245)"],
                        [0.6, "rgb(90, 120, 245)"], [0.7, "rgb(106, 137, 247)"], [1, "rgb(220, 220, 220)"]],
            autocolorscale=False,
            reversescale=True,
            marker=dict(
                line=dict(
                    color='rgb(180,180,180)',
                    width=0.5
                )),
            colorbar=dict(
                # autotick=False,
                title='Cluster Group'),
        )]

        layout = dict(
            title='K-Means Clustering Visualization',
            geo=dict(
                showframe=False,
                showcoastlines=False,
                projection=dict(
                    type='Mercator'
                )
            )
        )
        fig = dict(data=data, layout=layout)

        py.iplot(fig, validate=False, filename='d3-world-map')

        fig_path = 'choromap.png'
        py.image.save_as(fig, filename=fig_path)
        # convert to gif
        convert_png_to_gif(fig_path)
        # put in GUI
        photo = PhotoImage(file=fig_path.replace('png', 'gif'))
        self.horopleth_label.configure(image=photo, width='600px', height='600px')
        self.horopleth_label.image = photo
示例#55
0
    def show(self):
        self.__root.title(CONST.APP_NAME)
        mainFrame = Frame(self.__root)

        top = mainFrame.winfo_toplevel()
        top.rowconfigure(0, weight=1)
        top.columnconfigure(0, weight=1)
        mainFrame.rowconfigure(0, weight=1)
        mainFrame.columnconfigure(0, weight=1)
        mainFrame.grid(sticky='ew')

        # Three Sections: Input-Settings, Output-Settings and Buttons
        inputFrame = LabelFrame(mainFrame, text='Input Settings')
        inputFrame.columnconfigure(2, weight=1)
        inputFrame.grid(column=0, row=0, padx=5, pady=5, sticky='ew')
        outputFrame = LabelFrame(mainFrame, text='Output Settings')
        outputFrame.columnconfigure(2, weight=1)
        outputFrame.grid(column=0, row=1, padx=5, pady=5, sticky='ew')
        buttonFrame = Frame(mainFrame)
        buttonFrame.columnconfigure(3, weight=1)
        buttonFrame.grid(column=0, row=2, padx=5, pady=5, sticky='ew')

        # Input-Settings
        scribusSourceFileLabel = Label(inputFrame,
                                       text='Scribus File:',
                                       width=15,
                                       anchor='w')
        scribusSourceFileLabel.grid(column=0,
                                    row=0,
                                    padx=5,
                                    pady=5,
                                    sticky='w')
        scribusSourceFileEntry = Entry(
            inputFrame,
            textvariable=self.__ctrl.getScribusSourceFileEntryVariable())
        scribusSourceFileEntry.grid(column=1,
                                    columnspan=3,
                                    row=0,
                                    padx=5,
                                    pady=5,
                                    sticky='ew')
        scribusSourceFileButton = Button(
            inputFrame,
            text='⏏',
            command=self.__ctrl.scribusSourceFileEntryVariableHandler)
        scribusSourceFileButton.grid(column=4,
                                     row=0,
                                     padx=5,
                                     pady=5,
                                     sticky='e')
        scribusLoadSettingsButton = Button(
            inputFrame,
            text='↺',
            command=self.__ctrl.scribusLoadSettingsHandler)  # ⟲ ⟳ ↻ ↺ ⌂ ⌘ ⎗
        scribusLoadSettingsButton.grid(column=5,
                                       row=0,
                                       padx=5,
                                       pady=5,
                                       sticky='e')

        dataSourceFileLabel = Label(inputFrame,
                                    text='Data File:',
                                    width=15,
                                    anchor='w')
        dataSourceFileLabel.grid(column=0, row=1, padx=5, pady=5, sticky='w')
        dataSourceFileEntry = Entry(
            inputFrame,
            textvariable=self.__ctrl.getDataSourceFileEntryVariable())
        dataSourceFileEntry.grid(column=1,
                                 columnspan=4,
                                 row=1,
                                 padx=5,
                                 pady=5,
                                 sticky='ew')
        dataSourceFileButton = Button(
            inputFrame,
            text='⏏',
            command=self.__ctrl.dataSourceFileEntryVariableHandler)
        dataSourceFileButton.grid(column=5, row=1, padx=5, pady=5, sticky='e')

        dataSeparatorLabel = Label(inputFrame,
                                   text='Data Field Separator:',
                                   width=15,
                                   anchor='w')
        dataSeparatorLabel.grid(column=0, row=2, padx=5, pady=5, sticky='w')
        dataSeparatorEntry = Entry(
            inputFrame,
            width=3,
            textvariable=self.__ctrl.getDataSeparatorEntryVariable())
        dataSeparatorEntry.grid(column=1, row=2, padx=5, pady=5, sticky='w')

        fromLabel = Label(inputFrame,
                          text='(opt.) use partial data, only from:',
                          anchor='e')
        fromLabel.grid(column=2, row=2, padx=5, pady=5, sticky='e')
        fromEntry = Entry(inputFrame,
                          width=3,
                          textvariable=self.__ctrl.getFromVariable())
        fromEntry.grid(column=3, row=2, padx=5, pady=5, sticky='w')

        toLabel = Label(inputFrame, text='to:', width=3, anchor='e')
        toLabel.grid(column=4, row=2, padx=5, pady=5, sticky='e')
        toEntry = Entry(inputFrame,
                        width=3,
                        textvariable=self.__ctrl.getToVariable())
        toEntry.grid(column=5, row=2, padx=5, pady=5, sticky='w')

        # Output-Settings
        outputDirectoryLabel = Label(outputFrame,
                                     text='Output Directory:',
                                     width=15,
                                     anchor='w')
        outputDirectoryLabel.grid(column=0, row=0, padx=5, pady=5, sticky='w')
        outputDirectoryEntry = Entry(
            outputFrame,
            textvariable=self.__ctrl.getOutputDirectoryEntryVariable())
        outputDirectoryEntry.grid(column=1,
                                  columnspan=4,
                                  row=0,
                                  padx=5,
                                  pady=5,
                                  sticky='ew')
        outputDirectoryButton = Button(
            outputFrame,
            text='⏏',
            command=self.__ctrl.outputDirectoryEntryVariableHandler)
        outputDirectoryButton.grid(column=5, row=0, padx=5, pady=5, sticky='e')

        outputFileNameLabel = Label(outputFrame,
                                    text='Output File Name:',
                                    width=15,
                                    anchor='w')
        outputFileNameLabel.grid(column=0, row=1, padx=5, pady=5, sticky='w')
        outputFileNameEntry = Entry(
            outputFrame,
            textvariable=self.__ctrl.getOutputFileNameEntryVariable())
        outputFileNameEntry.grid(column=1,
                                 columnspan=3,
                                 row=1,
                                 padx=5,
                                 pady=5,
                                 sticky='ew')

        saveLabel = Label(outputFrame,
                          text='Save Settings:',
                          width=15,
                          anchor='w')
        saveLabel.grid(column=4, row=1, padx=5, pady=5, sticky='w')
        saveCheckbox = Checkbutton(
            outputFrame, variable=self.__ctrl.getSaveCheckboxVariable())
        saveCheckbox.grid(column=5, row=1, padx=5, pady=5, sticky='w')

        mergeOutputLabel = Label(outputFrame,
                                 text='Merge in Single File:',
                                 width=15,
                                 anchor='w')
        mergeOutputLabel.grid(column=0, row=2, padx=5, pady=5, sticky='w')
        mergeOutputCheckbox = Checkbutton(
            outputFrame, variable=self.__ctrl.getMergeOutputCheckboxVariable())
        mergeOutputCheckbox.grid(column=1, row=2, padx=5, pady=5, sticky='w')

        self.keepGeneratedScribusFilesLabel = Label(outputFrame,
                                                    text='Keep Scribus Files:',
                                                    width=15,
                                                    anchor='e')
        self.keepGeneratedScribusFilesLabel.grid(column=4,
                                                 row=2,
                                                 padx=5,
                                                 pady=5,
                                                 sticky='e')
        self.keepGeneratedScribusFilesCheckbox = Checkbutton(
            outputFrame,
            variable=self.__ctrl.getKeepGeneratedScribusFilesCheckboxVariable(
            ),
            anchor='w')
        self.keepGeneratedScribusFilesCheckbox.grid(column=5,
                                                    row=2,
                                                    padx=5,
                                                    pady=5,
                                                    sticky='w')

        outputFormatLabel = Label(outputFrame,
                                  text='Output Format:',
                                  anchor='e')
        outputFormatLabel.grid(column=2, row=2, padx=5, pady=5, sticky='e')
        outputFormatListBox = OptionMenu(
            outputFrame,
            self.__ctrl.getSelectedOutputFormat(),
            *self.__ctrl.getOutputFormatList(),
            command=lambda v=self.__ctrl.getSelectedOutputFormat(
            ): self.updateState(v))
        outputFormatListBox.grid(column=3, row=2, padx=5, pady=5, sticky='w')

        # Bottom Buttons
        generateButton = Button(buttonFrame,
                                text='✔\nGenerate',
                                width=10,
                                command=self.__ctrl.buttonOkHandler)
        generateButton.grid(column=0, row=0, padx=5, pady=5, sticky='w')
        cancelButton = Button(buttonFrame,
                              text='✘\nCancel',
                              width=10,
                              command=self.__ctrl.buttonCancelHandler)
        cancelButton.grid(column=1, row=0, padx=5, pady=5, sticky='e')
        helpButton = Button(buttonFrame,
                            text='❓\nHelp',
                            width=7,
                            command=self.__ctrl.helpButtonHandler)
        helpButton.grid(column=3, row=0, padx=5, pady=5, sticky='e')

        # general layout
        mainFrame.grid()
        self.__root.grid()
示例#56
0
 def _create_selector(self, parent, default, hidden):
     self._entry = Entry(parent, show='*' if hidden else '')
     self._entry.insert(0, default)
     self._entry.select_range(0, END)
     return self._entry
示例#57
0
class Clustering:
    def __init__(self, master):
        self.master = master
        master.title("Cluster")
        Tk().withdraw(
        )  # we don't want a full GUI, so keep the root window from appearing
        self.labelfile = Label(master, text="File:")
        self.entryfile = Entry(master, bd=2)
        self.choose_button = Button(master,
                                    text="Browse",
                                    command=lambda: self.browse())
        self.labelK = Label(master, text="Num of clusters k:")
        self.entryK = Entry(master, bd=2)
        self.labelRun = Label(master, text="Num of runs:")
        self.entryRun = Entry(master, bd=2)
        self.pre = Button(master, text="Pre-process", command=self.pre_proc)
        self.cluster = Button(master, text="Cluster", command=self.clustering)
        # LAYOUT
        self.labelfile.grid(row=0, column=0, sticky=W)
        self.entryfile.grid(row=1, column=0, columnspan=3, sticky=W + E)
        self.choose_button.grid(row=1, column=4)
        self.labelK.grid(row=2, column=0, sticky=W)
        self.entryK.grid(row=2, column=1, columnspan=3, sticky=W + E)
        self.labelRun.grid(row=3, column=0, sticky=W)
        self.entryRun.grid(row=3, column=1, columnspan=3, sticky=W + E)
        self.pre.grid(row=4, column=0)
        self.cluster.grid(row=4, column=1)
        self.model = None

    def pre_proc(self):
        try:
            input1 = self.entryK.get()
            input2 = self.entryRun.get()
            if self.validate(n1=input1, n2=input2, path=self.path):
                self.model = Model(path=self.path,
                                   KMeansNumber=input1,
                                   run_number=input2)
                self.cluster['state'] = 'normal'
                if (not self.model.preprocess()):
                    self.cluster['state'] = 'disabled'

        except Exception as error:
            tkMessageBox.showerror("Error", "path is not exist")
            self.cluster['state'] = 'disabled'

    def clustering(self):
        self.model.cluster()
        self.model.scatter()
        self.model.worldMap()
        self.showImages()
        tkMessageBox.showinfo("K Means Clustering",
                              "Clustering process finished successfully")

    def showImages(self):
        im = Image.open("./worldMap.png")
        resized = im.resize((500, 500), Image.ANTIALIAS)
        tkimage = ImageTk.PhotoImage(resized)
        myvar = Label(self.master, image=tkimage)
        myvar.image = tkimage
        myvar.grid(row=5, column=4)
        im2 = Image.open("./scatter.png")
        resized2 = im2.resize((500, 500), Image.ANTIALIAS)
        tkimage2 = ImageTk.PhotoImage(resized2)
        myvar = Label(self.master, image=tkimage2)
        myvar.image = tkimage2
        myvar.grid(row=5, column=0)


#check if the given inputs are numbers

    def validate(self, n1, n2, path):
        if n1.isdigit() != True or n2.isdigit() != True:
            tkMessageBox.showerror("K Means Clustering",
                                   "Please enter positive numbers")
            self.cluster['state'] = 'disabled'
            return False
        if not path:
            tkMessageBox.showerror("K Means Clustering",
                                   "Please browse a file")
            self.cluster['state'] = 'disabled'
            return False
        if not path.endswith(".xlsx"):
            tkMessageBox.showerror("K Means Clustering",
                                   "Please browse an xlsx file")
            self.cluster['state'] = 'disabled'
            return False
        return True

    def browse(self):
        filename = askopenfilename(
        )  # show an "Open" dialog box and return the path to the selected file
        self.entryfile.insert(0, filename)
        self.path = filename
示例#58
0
 def _create_selector(self, parent, default):
     self._entry = Entry(parent)
     self._entry.insert(0, default)
     self._entry.select_range(0, END)
     return self._entry
示例#59
-1
    def startUI(self):

        self.parent.title("Testing")

        self.file_list = listdir(getcwd())

        fileBox = Listbox(self.parent, selectmode=SINGLE)
        fileBox.pack()
        fileBox.grid(column=0, row=1, columnspan=3, rowspan=10, sticky=N + S)

        textBox = Text(self.parent)
        textBox.grid(column=4, row=0, columnspan=4, rowspan=10, sticky=N + S + E)

        ipBox = Entry(self.parent)
        ipBox.grid(column=0, row=0)

        btn = Button(text="Open ->", command=lambda: self.readFile(fileBox, textBox))
        btn.grid(column=3, row=2)

        btnFire = Button(text="Fire away!", command=lambda: self.fireTorpedoes(ipBox, textBox))
        btnFire.grid(column=3, row=3)

        scrlBar = Scrollbar(self.parent, command=textBox.yview)
        scrlBar.grid(column=8, row=0, rowspan=10, sticky=N + S)
        textBox.config(yscrollcommand=scrlBar.set)

        for i in self.file_list:
            fileBox.insert(END, i)
示例#60
-1
class Recherche(Vue):
    """
    Vue principal
    """
    def __init__(self, fenetre):
        """
        Constructeur de la fenetre
        """
        self.parent = fenetre
        self.frame = Frame(self.parent, borderwidth=1, relief='groove', width=100)
        self.frame.pack_configure(side='top', fill='both')
        self.frame.pack()
        self.titre = Label(self.frame, text=GT_('Url'), font=(20))
        self.titre.pack()
        self.img = PhotoImage(file="%slogo.gif" % RESSOURCES_PATH)
        self.logo = Label(self.frame, image=self.img)
        self.logo.pack(pady=(0, 20), side="left")
        self.brand = Label(self.frame, text=GT_('WebForge %s' % VERSION), font=(20))
        self.brand.pack(pady=(10, 20), padx=(0, 20), side="left")
        self.txt_recherche = Entry(self.frame, font=(22))
        self.txt_recherche.pack(pady=(0, 20), expand='yes', fill='both', side='left')
        self.btn_go = Button(self.frame, text="GO")
        self.btn_go.pack(pady=(0, 20), side='right')
        self.btn_erase = Button(self.frame, text="X")
        self.btn_erase.pack(pady=(0, 20), side='right')

    def set_url(self, url):
        """
        Set a new url value to the field
        """
        self.txt_recherche.insert(0, url)