コード例 #1
0
class MY_GUI():
    def __init__(self, init_window_name):
        self.init_window_name = init_window_name

    #设置窗口
    def set_init_window(self):
        ft1 = tkFont.Font(family='Arial', size=10, weight=tkFont.BOLD)
        ft_text = tkFont.Font(family='Arial', size=15)
        self.init_window_name.title("math quiz generator")
        #self.init_window_name.geometry('320x160+10+10')
        self.init_window_name.geometry('1000x700+10+10')
        # self.init_window_name["bg"] = "pink"
        # self.init_window_name.attributes("-alpha",0.9)

        self.choose_lable = Label(self.init_window_name,
                                  text="Please choose a Knowledge Component",
                                  font=ft1)
        self.choose_lable.grid(row=0, column=0, columnspan=2)

        # Drop down box
        from tkinter import ttk
        # self.drop_down_box = Combobox_Autocomplete(self.init_window_name, kc_list, listbox_width=150, highlightthickness=1)
        # self.drop_down_box.focus()
        self.drop_down_box = AutocompleteCombobox(self.init_window_name,
                                                  completevalues=kc_list,
                                                  width=150)
        self.drop_down_box.grid(row=1, column=0, columnspan=2)

        self.choose_language_label = Label(self.init_window_name,
                                           text="Please choose language",
                                           font=ft1)
        self.choose_language_label.grid(row=2, column=0)
        self.choose_language_box = ttk.Combobox(self.init_window_name,
                                                values=['English', 'Dutch'],
                                                width=50)
        self.choose_language_box.grid(row=3, column=0)
        self.is_retrieve = BooleanVar()
        self.choose_retrieve_button = ttk.Checkbutton(
            self.init_window_name,
            text='Retrieve Image or Not',
            variable=self.is_retrieve)
        self.choose_retrieve_button.grid(row=3, column=1)

        # Button
        self.str_generate_button = Button(self.init_window_name,
                                          text="Generate",
                                          bg="lightblue",
                                          width=10,
                                          command=self.generator)
        self.str_generate_button.grid(row=4, column=0, columnspan=2)
        self.result_data_label = Label(self.init_window_name,
                                       text="Generated question",
                                       font=ft1)
        self.result_data_label.grid(row=9, column=0)

        self.result_data_Text = Text(self.init_window_name, width=50)
        self.result_data_Text.grid(row=10, column=0)
        self.answer_label = Label(self.init_window_name,
                                  text="Answer",
                                  font=ft1)
        self.answer_label.grid(row=9, column=1)
        self.answer_data_Text = Text(self.init_window_name, width=50)
        self.answer_data_Text.grid(row=10, column=1)
        self.image_label = Label(self.init_window_name, text="Image", font=ft1)
        self.image_label.grid(row=11, column=0, columnspan=2)
        self.image_data_Text = Text(self.init_window_name, width=100)
        self.image_data_Text.grid(row=12, column=0, columnspan=2)
        self.img_label = Label(self.init_window_name, image=None)

    def generator(self):
        self.img_label.grid_forget()
        kc = self.drop_down_box.get()
        language = self.choose_language_box.get()
        kc_no = kc[0:kc.index('-') - 1]
        from overall_menu import Menu
        if language == 'Dutch':
            m = Menu(int(kc_no), 'nl', self.is_retrieve.get())
        else:
            m = Menu(int(kc_no), 'en', self.is_retrieve.get())
        question, answer, img_dir_list = m.menu()
        if len(question) == 0:
            question = "Sorry we can not generate text question for this KC"
        self.result_data_Text.delete(1.0, 'end')
        self.result_data_Text.insert(END, question)
        self.answer_data_Text.delete(1.0, 'end')
        self.answer_data_Text.insert(END, answer)
        from PIL import Image, ImageTk
        self.image_data_Text.delete(1.0, 'end')
        for img_dir in img_dir_list:
            self.image_data_Text.insert(END, str(img_dir))
            self.image_data_Text.insert(END, '\n')
            # img = Image.open(img_dir)
            # w, h = img.size
            # ws = 500
            # hs = h * ws / w
            # img = img.resize((ws,int(hs)), Image.ANTIALIAS)
            # photo = ImageTk.PhotoImage(img)
            # self.img_label.config(image=photo)
            # self.img_label.grid(row=12, column=0, columnspan=2)

        self.init_window_name.mainloop()
コード例 #2
0
class StartPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.config(pady=100)
        self.top_frame = tk.Frame(self,
                                  background="#f5f5f5",
                                  width=700,
                                  pady=10,
                                  padx=10)
        self.frame = tk.Frame(self.top_frame,
                              background="#f5f5f5",
                              height=200,
                              width=700,
                              pady=10)
        self.frame.grid_propagate(False)

        self.label1 = ttk.Label(self, text="Welcome!", font=LARGE_FONT)

        self.button1 = ttk.Button(
            self,
            text="Visit Page 1",
            command=lambda: controller.show_frame(PageOne))

        self.button2 = ttk.Button(
            self,
            text="Visit Page 2",
            command=lambda: controller.show_frame(PageTwo))

        self.button_test = ttk.Button(self.frame,
                                      text="Choose File",
                                      command=lambda: self.get_file_path())

        self.label_welcome = ttk.Label(self.top_frame,
                                       text="Welcome!",
                                       font=("Helvetica", 16, 'bold'))
        self.label_point_notes = ttk.Label(self.frame,
                                           text="Notes",
                                           font=("Helvetica", 14, 'bold'))
        self.label_point1 = ttk.Label(self.frame,
                                      text="-> This is point 1",
                                      font=("Helvetica", 14))
        self.dropdown = ttk.OptionMenu(self, tk.StringVar(), "First value",
                                       "Second Value")
        self.entry = ttk.Entry(
            self, textvariable=tk.StringVar(value="Default entry value."))
        self.button = ttk.Button(self, text="Button")
        self.radio_one = ttk.Radiobutton(self, text="Radio one", value=True)
        self.radio_two = ttk.Radiobutton(self, text="Radio two", value=False)
        self.scroll = ttk.Scrollbar(self, orient=tk.VERTICAL)
        self.checked = ttk.Checkbutton(self,
                                       text="Checked",
                                       variable=tk.BooleanVar(value=True))
        self.unchecked = ttk.Checkbutton(self, text="Unchecked")
        self.tree = ttk.Treeview(self, height=4, show=("tree", "headings"))
        self.setup_tree()
        self.scale_entry = ScaleEntry(self,
                                      from_=0,
                                      to=50,
                                      orient=tk.HORIZONTAL,
                                      compound=tk.RIGHT)
        self.combo = AutocompleteCombobox(
            self, completevalues=["something", "something else"])
        self.progress = ttk.Progressbar(self, maximum=100, value=50)
        # Grid widgets
        self.set_grid_widgets()

    def get_file_path(self):
        self.filepath = tk.filedialog.askopenfilename()
        print(self.filepath)

    def setup_tree(self):
        """Setup an example Treeview"""
        self.tree.insert("", tk.END, text="Example 1", iid="1")
        self.tree.insert("", tk.END, text="Example 2", iid="2")
        self.tree.insert("2", tk.END, text="Example Child")
        self.tree.heading("#0", text="Example heading")

    def set_grid_widgets(self):
        """Put widgets in the grid"""
        sticky = {"sticky": "nswe"}
        self.label_welcome.grid(row=0, column=0)
        self.label_point_notes.grid(row=0, column=0)
        self.label_point1.grid(row=1, column=0)
        self.button_test.grid(row=2, column=0)
        self.frame.grid(row=1, column=0)
        self.top_frame.grid(row=0, column=0)
        self.top_frame.columnconfigure(0, weight=1)
        self.columnconfigure(0, weight=1)

    def grid_widgets(self):
        """Put widgets in the grid"""
        sticky = {"sticky": "nswe"}
        self.button1.grid(row=0, column=1, columnspan=2, **sticky)
        self.button2.grid(row=1, column=1, columnspan=2, **sticky)
        self.label1.grid(row=1, column=1, columnspan=2, **sticky)
        self.dropdown.grid(row=2, column=1, **sticky)
        self.entry.grid(row=2, column=2, **sticky)
        self.button.grid(row=3, column=1, columnspan=2, **sticky)
        self.radio_one.grid(row=4, column=1, **sticky)
        self.radio_two.grid(row=4, column=2, **sticky)
        self.checked.grid(row=5, column=1, **sticky)
        self.unchecked.grid(row=5, column=2, **sticky)
        self.scroll.grid(row=1, column=3, rowspan=8, padx=5, **sticky)
        self.tree.grid(row=6, column=1, columnspan=2, **sticky)
        self.scale_entry.grid(row=7, column=1, columnspan=2, **sticky)
        self.combo.grid(row=8, column=1, columnspan=2, **sticky)
        self.progress.grid(row=9,
                           column=1,
                           columnspan=2,
                           padx=5,
                           pady=5,
                           **sticky)
コード例 #3
0
class Example(ThemedTk):
    """
    Example that is used to create screenshots for new themes.
    """
    def __init__(self):
        ThemedTk.__init__(self, themebg=True)
        # Create widgets
        self.menu = tk.Menu(self, tearoff=False)
        self.sub_menu = tk.Menu(self.menu, tearoff=False)
        self.sub_menu.add_command(label="Exit", command=self.destroy)
        self.menu.add_cascade(menu=self.sub_menu, label="General")
        self.config(menu=self.menu)
        self.label = ttk.Label(self, text="This is an example label.")
        self.dropdown = ttk.OptionMenu(self, tk.StringVar(), "First value",
                                       "Second Value")
        self.entry = ttk.Entry(
            self, textvariable=tk.StringVar(value="Default entry value."))
        self.button = ttk.Button(self, text="Button")
        self.radio_one = ttk.Radiobutton(self, text="Radio one", value=True)
        self.radio_two = ttk.Radiobutton(self, text="Radio two", value=False)
        self.scroll = ttk.Scrollbar(self, orient=tk.VERTICAL)
        self.checked = ttk.Checkbutton(self,
                                       text="Checked",
                                       variable=tk.BooleanVar(value=True))
        self.unchecked = ttk.Checkbutton(self, text="Unchecked")
        self.tree = ttk.Treeview(self, height=4, show=("tree", "headings"))
        self.setup_tree()
        self.scale_entry = ScaleEntry(self,
                                      from_=0,
                                      to=50,
                                      orient=tk.HORIZONTAL,
                                      compound=tk.RIGHT)
        self.combo = AutocompleteCombobox(
            self, completevalues=["something", "something else"])
        self.progress = ttk.Progressbar(self, maximum=100, value=50)
        # Grid widgets
        self.grid_widgets()
        # Bind screenshot button
        self.bind("<F10>", self.screenshot)
        self.bind("<F9>", self.screenshot_themes)

    def setup_tree(self):
        """Setup an example Treeview"""
        self.tree.insert("", tk.END, text="Example 1", iid="1")
        self.tree.insert("", tk.END, text="Example 2", iid="2")
        self.tree.insert("2", tk.END, text="Example Child")
        self.tree.heading("#0", text="Example heading")

    def grid_widgets(self):
        """Put widgets in the grid"""
        sticky = {"sticky": "nswe"}
        self.label.grid(row=1, column=1, columnspan=2, **sticky)
        self.dropdown.grid(row=2, column=1, **sticky)
        self.entry.grid(row=2, column=2, **sticky)
        self.button.grid(row=3, column=1, columnspan=2, **sticky)
        self.radio_one.grid(row=4, column=1, **sticky)
        self.radio_two.grid(row=4, column=2, **sticky)
        self.checked.grid(row=5, column=1, **sticky)
        self.unchecked.grid(row=5, column=2, **sticky)
        self.scroll.grid(row=1, column=3, rowspan=8, padx=5, **sticky)
        self.tree.grid(row=6, column=1, columnspan=2, **sticky)
        self.scale_entry.grid(row=7, column=1, columnspan=2, **sticky)
        self.combo.grid(row=8, column=1, columnspan=2, **sticky)
        self.progress.grid(row=9,
                           column=1,
                           columnspan=2,
                           padx=5,
                           pady=5,
                           **sticky)

    def screenshot(self, *args):
        """Take a screenshot, crop and save"""
        from mss import mss
        if not os.path.exists("screenshots"):
            os.makedirs("screenshots")
        box = {
            "top": self.winfo_y(),
            "left": self.winfo_x(),
            "width": self.winfo_width(),
            "height": self.winfo_height()
        }
        screenshot = mss().grab(box)
        screenshot = Image.frombytes("RGB", screenshot.size, screenshot.rgb)
        screenshot.save("screenshots/{}.png".format(
            ttk.Style(self).theme_use()))

    def screenshot_themes(self, *args):
        """Take a screenshot for all themes available"""
        from time import sleep
        for theme in THEMES:
            example.set_theme(theme)
            example.update()
            sleep(0.05)
            self.screenshot()
コード例 #4
0
class Example(ThemedTk):
    """
    Example that is used to create screenshots for new themes.
    """
    def __init__(self, theme="arc"):
        """
        :param theme: Theme to show off
        """
        ThemedTk.__init__(self)
        self.set_theme(theme)
        # Create widgets
        self.label = ttk.Label(self, text="This is an example label.")
        self.dropdown = ttk.OptionMenu(self, tk.StringVar(), "First value")
        self.entry = ttk.Entry(
            self, textvariable=tk.StringVar(value="Default entry value."))
        self.button = ttk.Button(self, text="Button")
        self.radio_one = ttk.Radiobutton(self, text="Radio one")
        self.radio_two = ttk.Radiobutton(self, text="Radio two")
        self.scroll = ttk.Scrollbar(self, orient=tk.VERTICAL)
        self.checked = ttk.Checkbutton(self,
                                       text="Checked",
                                       variable=tk.BooleanVar(value=True))
        self.unchecked = ttk.Checkbutton(self, text="Unchecked")
        self.tree = ttk.Treeview(self, height=4, show=("tree", ))
        self.setup_tree()
        self.scale_entry = ScaleEntry(self,
                                      from_=0,
                                      to=50,
                                      orient=tk.HORIZONTAL,
                                      compound=tk.RIGHT)
        self.combo = AutocompleteCombobox(
            self, completevalues=["something", "something else"])
        # Grid widgets
        self.grid_widgets()
        # Bind screenshot button
        self.bind("<F10>", self.screenshot)

    def setup_tree(self):
        """Setup an example Treeview"""
        self.tree.insert("", tk.END, text="Example 1", iid="1")
        self.tree.insert("", tk.END, text="Example 2", iid="2")
        self.tree.insert("2", tk.END, text="Example Child")

    def grid_widgets(self):
        """Put widgets in the grid"""
        sticky = {"sticky": "nswe"}
        self.label.grid(row=1, column=1, columnspan=2, **sticky)
        self.dropdown.grid(row=2, column=1, **sticky)
        self.entry.grid(row=2, column=2, **sticky)
        self.button.grid(row=3, column=1, columnspan=2, **sticky)
        self.radio_one.grid(row=4, column=1, **sticky)
        self.radio_two.grid(row=4, column=2, **sticky)
        self.checked.grid(row=5, column=1, **sticky)
        self.unchecked.grid(row=5, column=2, **sticky)
        self.scroll.grid(row=1, column=3, rowspan=8, **sticky, padx=5)
        self.tree.grid(row=6, column=1, columnspan=2, **sticky)
        self.scale_entry.grid(row=7, column=1, columnspan=2, **sticky)
        self.combo.grid(row=8, column=1, columnspan=2, **sticky)

    def screenshot(self, *args):
        """Take a screenshot, crop and save"""
        from mss import mss
        box = {
            "top": self.winfo_y(),
            "left": self.winfo_x(),
            "width": self.winfo_width(),
            "height": self.winfo_height()
        }
        screenshot = mss().grab(box)
        screenshot = Image.frombytes("RGB", screenshot.size, screenshot.rgb)
        screenshot.save("screenshot.png")
コード例 #5
0
ファイル: input.py プロジェクト: Bomberus/LayoutX
class FileInput(BaseInput):
  def __init__(self, master, **kwargs):
    self._onlydir = False
    self._ext = ('Any File', '.*')
    self._rootdir = None
    self._excludefiles = []
    self._suggestions = []
    self._file_suggestions = None

    self._textv = StringVar()
    self._box = ttk.Frame(master=master)
    self._box.grid_columnconfigure(0, weight=1)
    self._box.grid_columnconfigure(1, weight=0)
    self._box.grid_rowconfigure(0, weight=1)
    
    self._input = AutocompleteCombobox(
      master=self._box,
      completevalues=[],
      textvariable=self._textv
    )

    # Redirect configure to input
    setattr(self._box, "config", self._input.config)
    setattr(self._box, "configure", self._input.configure)
    setattr(self._box, "keys", self._input.keys)
    setattr(self._box, "cget", self._input.cget)
    setattr(self._box, "winfo_class", self._input.winfo_class)
    setattr(self._box, "bind", self._input.bind)
    setattr(self._box, "set_completion_list", self._input.set_completion_list)

    super().__init__(tk=self._box, **kwargs)
    self.connect_to_prop("onlydir", self._on_onlydir_changed)
    self.connect_to_prop("ext", self._on_ext_changed)
    self.connect_to_prop("rootdir", self._on_rootdir_changed)
    self.connect_to_prop("excludefiles", self._on_excludefiles_changed)
    #self.connect_to_prop("suggestion", self.on_changed_suggestion)
    
    self._input.drop_target_register(DND_FILES)
    self._input.dnd_bind('<<Drop>>', self._drop)
    self._input.grid(row=0, column=0, sticky="news")

    self._btn = ttk.Button(master=self._box, command=self._load_file, text="Browse...")
    self._btn.grid(row=0, column=1)

  def _on_excludefiles_changed(self, value):
    self._excludefiles = value if value else []
    self._set_suggestions() 
  
  def _on_onlydir_changed(self, value):
    self._onlydir = value
  
  def on_changed_suggestion(self, value):
    if value:
      self._suggestions = value
      self._set_suggestions()

  def _set_suggestions(self):
    if self._rootdir and Path(self._rootdir).exists() and self._file_suggestions == None:
      get_suggestion_from_ext = lambda ext: list(filter(lambda fn: Path(fn).stem not in self._excludefiles, [str(fn) for fn in Path(self._rootdir).rglob(f"*{ext[1]}")]))
      
      if isinstance(self._ext, list):
        from functools import reduce
        self._file_suggestions = reduce(lambda a, curr: a + get_suggestion_from_ext(curr), [])
      else:
        self._file_suggestions = get_suggestion_from_ext(self._ext)
    if isinstance(self._file_suggestions, list):
      self._input.set_completion_list(self._suggestions + self._file_suggestions)
    else:
      self._input.set_completion_list(self._suggestions)

  def _on_ext_changed(self, value):
    self._ext = value if value else ('Any File', '.*')
    self._set_suggestions()
    
  def _on_rootdir_changed(self, value):
    self._rootdir = value
    self._set_suggestions()

  @property
  def container(self):
    return self._box

  def on_disposed(self):
    self._box.destroy()
    self._btn.destroy()
    super().on_disposed()
  
  def _load_file(self):
    if self._onlydir:
      f = tk.filedialog.askdirectory() 
    else:
      f = tk.filedialog.askopenfilename(filetypes=self._ext if isinstance(self._ext, list) else [self._ext])
    if f is None or f == '':
      return
    self._textv.set(str(Path(f)))

  def _drop(self, event):
    if event.data:
      files = self._tk.tk.splitlist(event.data)
      for f in files:
        self._textv.set(f)
        break
    return event.action
コード例 #6
0
# widgets griding
d_pad = {"padx": 5, "pady": 5, "sticky": "NSEW"}
ent_search.grid(row=1, columnspan=2, **d_pad)

lbl_actions.grid(row=2, column=0, **d_pad)
lbl_contacts.grid(row=2, column=1, **d_pad)
lbl_formats.grid(row=4, column=0, **d_pad)
lbl_inspires.grid(row=4, column=1, **d_pad)
lbl_keywords.grid(row=6, column=0, **d_pad)
lbl_licenses.grid(row=6, column=1, **d_pad)
lbl_owners.grid(row=8, column=0, **d_pad)
lbl_shares.grid(row=8, column=1, **d_pad)
lbl_srs.grid(row=10, column=0, **d_pad)
lbl_types.grid(row=10, column=1, **d_pad)

cb_fltr_actions.grid(row=3, column=0, **d_pad)
cb_fltr_contacts.grid(row=3, column=1, **d_pad)
cb_fltr_formats.grid(row=5, column=0, **d_pad)
cb_fltr_inspires.grid(row=5, column=1, **d_pad)
cb_fltr_keywords.grid(row=7, column=0, **d_pad)
cb_fltr_licenses.grid(row=7, column=1, **d_pad)
cb_fltr_owners.grid(row=9, column=0, **d_pad)
cb_fltr_shares.grid(row=9, column=1, **d_pad)
cb_fltr_srs.grid(row=11, column=0, **d_pad)
cb_fltr_types.grid(row=11, column=1, **d_pad)

button.grid(row=25, columnspan=2, **d_pad)

# balloon tooltips
balloon = Balloon(button)
コード例 #7
0
 def __init__(self, *args, **kwargs):
     """Configure the GUI and other important features (load peak locations)"""
     tk.Tk.__init__(self, *args, **kwargs)
     self.title("PGAA Data Analysis App")
     
     sens_file = open("AllSensitivity.csv")
     self.all_peaks_sens = [line.strip(" ").split(",") for line in sens_file.read().split("\n")][:-1]
     sens_file.close()
     
     menuBar = tk.Menu(self, tearoff=0)
     
     fileMenu = tk.Menu(menuBar, tearoff=0)
     fileMenu.add_command(label="Add File(s)", command = lambda:self.add_files(tk.filedialog.askopenfilenames(initialdir = ".",title = "Select files",filetypes = [("Spectrum files","*.spe"), ("Canberra CNF Files","*.cnf")])))
     fileMenu.add_command(label="Remove File(s)", command = self.remove_file_GUI)
     menuBar.add_cascade(label="File",menu=fileMenu)
     
     editMenu = tk.Menu(menuBar, tearoff=0)
     editMenu.add_command(label="ROIs", command = self.edit_ROIs_GUI)
     menuBar.add_cascade(label="Edit",menu=editMenu)
     
     viewMenu = tk.Menu(menuBar, tearoff=0)
     viewMenu.add_command(label="Side-by-Side", command = self.side_to_side_GUI)
     viewMenu.add_command(label="Zoom to ROI", command = self.ROIZoomGUI)
     menuBar.add_cascade(label="View",menu=viewMenu)
     
     analyzeMenu = tk.Menu(menuBar, tearoff=0)
     analyzeMenu.add_command(label="Elemental Analysis", command = self.Elemental_Analysis_GUI)
     analyzeMenu.add_command(label="Decomposition Analysis", command = lambda:0)
     menuBar.add_cascade(label="Analyze",menu=analyzeMenu)
     
     self.config(menu=menuBar)
     
     graphInfo = tk.Frame(self)
     
     tk.Label(graphInfo, text="Current File:").grid(row=0,column=0)
     self.selectedFile = tk.StringVar()
     self.fileSelector = ttk.OptionMenu(graphInfo, self.selectedFile, "No Files to Display", command=self.change_file)
     self.fileSelector.grid(row=0,column=1, padx=(0,75))
     
     tk.Label(graphInfo, text="Livetime:").grid(row=0,column=2)
     self.currentLivetime = tk.Label(graphInfo, text="    N/A    ", borderwidth=2, relief="sunken")
     self.currentLivetime.grid(row=0,column=3, padx=(0,20))
     tk.Label(graphInfo, text="Realtime:").grid(row=0,column=4)
     self.currentRealtime = tk.Label(graphInfo, text="    N/A    ", borderwidth=2, relief="sunken")
     self.currentRealtime.grid(row=0,column=5)
     graphInfo.grid(row=0,column=1, pady=(10,0))
     
     f = Figure(figsize=(7,3), dpi=100)
     self.plotAxes = f.add_subplot(111)
     f.subplots_adjust(bottom=0.15)
     self.plotAxes.set_xlabel("Energy (kEv)")
     self.plotAxes.set_ylabel("Counts Per Second")
     self.canvas = FigureCanvasTkAgg(f, self)
     self.canvas.draw()
     self.canvas.get_tk_widget().grid(row=1,column=0,columnspan=6, rowspan=6)
     toolbarFrame = tk.Frame(self)
     toolbarFrame.grid(row=8,column=0,columnspan=6, sticky="w")
     toolbar = NavigationToolbar2Tk(self.canvas, toolbarFrame)
     toolbar._Spacer()
     self.scaleChangeButton = tk.Button(toolbar, text="LOG", command=self.toggle_y_scale)
     self.scaleChangeButton.pack(side="left")
     
     win = tk.Toplevel()
     win.wm_title("Edit ROIs")
     ttk.Label(win, text="Add/Remove Elements of Interest:").grid(row=0,column=0,columnspan=2)
     elementsList = list(set(map(lambda x: x[0], self.all_peaks_sens)))
     self.comboValue = tk.StringVar()
     combo = AutocompleteCombobox(win, elementsList, textvariable=self.comboValue)
     combo.grid(row=1,column=0)
     ttk.Button(win, text="Add", command=lambda: self.add_element(win, self.elementIndex, self.comboValue.get())).grid(row=1, column=1)
     self.eleLabelList = []
     self.removeBtnList = []
     self.elementIndex = 2
     ttk.Button(win, text="Submit", command=self.edit_ROIs).grid(row=1000,column=0, columnspan=2)
     self.ROIEditWindow = win
     self.ROIEditWindow.withdraw()
     self.ROIEditWindow.protocol("WM_DELETE_WINDOW", self.ROIEditWindow.withdraw)
     
     self.files = []
     self.fileInfo = []
     self.elements = []
     self.polyFills = []
     self.fitIndices = []
     self.fitRanges = []
     self.graphEnergies = []
     self.graphCPS = []
     self.selectionList = []
     self.isotopes = []
コード例 #8
0
ファイル: main.py プロジェクト: 2015hcm/hello-world
    def __init__(self, *args, **kwargs):
        """Configure the GUI and other important features (load peak locations)"""
        tk.Tk.__init__(self, *args, **kwargs)
        self.title("PGAA Data Analysis App")

        sens_file = open("AllSensitivity.csv")
        self.all_peaks_sens = [
            line.strip(" ").split(",") for line in sens_file.read().split("\n")
        ][:-1]
        sens_file.close()

        menuBar = tk.Menu(self, tearoff=0)

        fileMenu = tk.Menu(menuBar, tearoff=0)
        fileMenu.add_command(label="Add File(s)",
                             command=lambda: self.add_files(
                                 tk.filedialog.askopenfilenames(
                                     initialdir=".",
                                     title="Select files",
                                     filetypes=[("Spectrum files", "*.spe")])))
        fileMenu.add_command(label="Remove File(s)",
                             command=self.remove_file_GUI)
        menuBar.add_cascade(label="File", menu=fileMenu)

        editMenu = tk.Menu(menuBar, tearoff=0)
        editMenu.add_command(label="ROIs", command=self.edit_ROIs_GUI)
        menuBar.add_cascade(label="Edit", menu=editMenu)

        viewMenu = tk.Menu(menuBar, tearoff=0)
        viewMenu.add_command(label="Side-by-Side",
                             command=self.side_to_side_GUI)
        viewMenu.add_command(label="Zoom to ROI", command=self.ROIZoomGUI)
        menuBar.add_cascade(label="View", menu=viewMenu)

        analyzeMenu = tk.Menu(menuBar, tearoff=0)
        analyzeMenu.add_command(label="Elemental Analysis",
                                command=self.Elemental_Analysis_GUI)
        analyzeMenu.add_command(label="Decomposition Analysis",
                                command=lambda: 0)
        menuBar.add_cascade(label="Analyze", menu=analyzeMenu)

        self.config(menu=menuBar)

        graphInfo = tk.Frame(self)

        tk.Label(graphInfo, text="Current File:").grid(row=0, column=0)
        self.selectedFile = tk.StringVar()
        self.fileSelector = ttk.OptionMenu(graphInfo,
                                           self.selectedFile,
                                           "No Files to Display",
                                           command=self.change_file)
        self.fileSelector.grid(row=0, column=1, padx=(0, 75))

        tk.Label(graphInfo, text="Livetime:").grid(row=0, column=2)
        self.currentLivetime = tk.Label(graphInfo,
                                        text="    N/A    ",
                                        borderwidth=2,
                                        relief="sunken")
        self.currentLivetime.grid(row=0, column=3, padx=(0, 20))
        tk.Label(graphInfo, text="Realtime:").grid(row=0, column=4)
        self.currentRealtime = tk.Label(graphInfo,
                                        text="    N/A    ",
                                        borderwidth=2,
                                        relief="sunken")
        self.currentRealtime.grid(row=0, column=5)
        graphInfo.grid(row=0, column=1, pady=(10, 0))

        f = Figure(figsize=(7, 3), dpi=100)
        self.plotAxes = f.add_subplot(111)
        f.subplots_adjust(bottom=0.15)
        self.plotAxes.set_xlabel("Energy (kEv)")
        self.plotAxes.set_ylabel("Counts Per Second")
        self.canvas = FigureCanvasTkAgg(f, self)
        self.canvas.draw()
        self.canvas.get_tk_widget().grid(row=1,
                                         column=0,
                                         columnspan=6,
                                         rowspan=6)
        toolbarFrame = tk.Frame(self)
        toolbarFrame.grid(row=8, column=0, columnspan=6, sticky="w")
        toolbar = NavigationToolbar2Tk(self.canvas, toolbarFrame)
        toolbar.children['!button6'].pack_forget()
        toolbar._Spacer()
        self.scaleChangeButton = tk.Button(toolbar,
                                           text="LOG",
                                           command=self.toggle_y_scale)
        self.scaleChangeButton.pack(side="left")

        win = tk.Toplevel()
        win.wm_title("Edit ROIs")
        ttk.Label(win,
                  text="Add/Remove Elements of Interest:").grid(row=0,
                                                                column=0,
                                                                columnspan=2)
        elementsList = [
            'Actinium', 'Aluminum', 'Americium', 'Antimony', 'Argon',
            'Arsenic', 'Astatine', 'Barium', 'Berkelium', 'Beryllium',
            'Bismuth', 'Bohrium', 'Boron', 'Bromine', 'Cadmium', 'Calcium',
            'Californium', 'Carbon', 'Cerium', 'Cesium', 'Chlorine',
            'Chromium', 'Cobalt', 'Copper', 'Curium', 'Darmstadtium',
            'Dubnium', 'Dysprosium', 'Einsteinium', 'Erbium', 'Europium',
            'Fermium', 'Fluorine', 'Francium', 'Gadolinium', 'Gallium',
            'Germanium', 'Gold', 'Hafnium', 'Hassium', 'Helium', 'Holmium',
            'Hydrogen', 'Indium', 'Iodine', 'Iridium', 'Iron', 'Krypton',
            'Lanthanum', 'Lawrencium', 'Lead', 'Lithium', 'Lutetium',
            'Magnesium', 'Manganese', 'Meitnerium', 'Mendelevium', 'Mercury',
            'Molybdenum', 'Neodymium', 'Neon', 'Neptunium', 'Nickel',
            'Niobium', 'Nitrogen', 'Nobelium', 'Oganesson', 'Osmium', 'Oxygen',
            'Palladium', 'Phosphorus', 'Platinum', 'Plutonium', 'Polonium',
            'Potassium', 'Praseodymium', 'Promethium', 'Protactinium',
            'Radium', 'Radon', 'Rhenium', 'Rhodium', 'Roentgenium', 'Rubidium',
            'Ruthenium', 'Rutherfordium', 'Samarium', 'Scandium', 'Seaborgium',
            'Selenium', 'Silicon', 'Silver', 'Sodium', 'Strontium', 'Sulfur',
            'Tantalum', 'Technetium', 'Tellurium', 'Terbium', 'Thallium',
            'Thorium', 'Thulium', 'Tin', 'Titanium', 'Tungsten', 'Ununbium',
            'Ununhexium', 'Ununpentium', 'Ununquadium', 'Ununseptium',
            'Ununtrium', 'Uranium', 'Vanadium', 'Xenon', 'Ytterbium',
            'Yttrium', 'Zinc', 'Zirconium'
        ]
        self.comboValue = tk.StringVar()
        combo = AutocompleteCombobox(win,
                                     elementsList,
                                     textvariable=self.comboValue)
        combo.grid(row=1, column=0)
        ttk.Button(win,
                   text="Add",
                   command=lambda: self.add_element(
                       win, self.elementIndex, self.comboValue.get())).grid(
                           row=1, column=1)
        self.eleLabelList = []
        self.removeBtnList = []
        self.elementIndex = 2
        ttk.Button(win, text="Submit",
                   command=self.edit_ROIs).grid(row=1000,
                                                column=0,
                                                columnspan=2)
        self.ROIEditWindow = win
        self.ROIEditWindow.withdraw()
        self.ROIEditWindow.protocol("WM_DELETE_WINDOW",
                                    self.ROIEditWindow.withdraw)

        self.files = []
        self.fileInfo = []
        self.elements = []
        self.polyFills = []
        self.fitIndices = []
        self.fitRanges = []
        self.graphEnergies = []
        self.graphCPS = []
        self.selectionList = []
deg_rad_button.bind('<FocusIn>',lambda event: deg_rad_button.config(bg='MediumPurple1'))
deg_rad_button.bind('<FocusOut>',lambda event: deg_rad_button.config(bg='hot pink') if deg_rad_var.get()==0 else deg_rad_button.config(bg='turquoise1'))

button_backspace=HoverButton(window,text='\u232b',font=font,fg="Black",borderwidth=0,bg='white',command=backspace,activebackground=active_button_background,takefocus=0)
button_backspace.grid(row=6,column=2,sticky='news',padx=5,pady=5)

button_clear_all=HoverButton(window,text='\u239a',font=font,fg="Black",borderwidth=0,bg='white',command=clear_input,activebackground=active_button_background,takefocus=0)
button_clear_all.grid(row=6,column=3,sticky='news',padx=5,pady=5)

function_dropdown=AutocompleteCombobox(window,width=5,textvariable=function_input_var,font=font)
function_dropdown['completevalues']=function_list
function_dropdown.bind('<Key>',function_select)
function_dropdown.bind('<Double-Button-1>',function_select)
function_dropdown.autocomplete(delta=-6)
function_dropdown.current()
function_dropdown.grid(row=7,column=0,sticky='news',padx=5,pady=5,columnspan=3)

save_and_clear_all=HoverButton(window,text='\u21ba',font=font,fg="Black",borderwidth=0,bg='white',command=save_and_clear_input,activebackground=active_button_background,takefocus=0)
save_and_clear_all.grid(row=7,column=3,sticky='news',padx=5,pady=5)

button_Ans=HoverButton(window,text='Ans',font=font,fg="Black",borderwidth=0,bg='white',command=lambda: input_to_input_var('Ans'),activebackground=active_button_background,takefocus=0)
button_Ans.grid(row=7,column=4,sticky='news',padx=5,pady=5)

size_spinbox=tk.Spinbox(window,from_=0,to=100,font=font,fg="Black",bg="white",textvariable=size_var,width=4,command=lambda: resize(1),takefocus=1)
size_spinbox.bind('<Key>',resize)
size_spinbox.grid(row=2,column=4,sticky='news',padx=5,pady=5)

button_pi=HoverButton(window,text='\u03c0',font=font,fg="Black",borderwidth=0,bg='white',command=lambda: input_to_input_var('pi'),activebackground=active_button_background,takefocus=0)
button_pi.grid(row=3,column=4,sticky='news',padx=5,pady=5)

button_e=HoverButton(window,text='e',font=font,fg="Black",borderwidth=0,bg='white',command=lambda: input_to_input_var('e'),activebackground=active_button_background,takefocus=0)
コード例 #10
0
class IsogeoSearchForm(ttk.Frame):
    def __init__(self, master=None, async_loop=None):
        tk.Frame.__init__(self, master)
        self.async_loop = async_loop

        # basics
        # master.resizable(width=True, height=True)
        master.title(
            "Isogeo Python SDK v{} - Sample desktop search form".format(pysdk_version)
        )
        master.focus_force()
        self.grid(sticky="NSWE")
        self.grid_propagate(1)

        # styling
        self.style = ttk.Style(self)

        self.s1 = tk.PhotoImage(
            master=self, name="search1", data=data, format="gif -index 0"
        )
        self.s2 = tk.PhotoImage(
            master=self, name="search2", data=data, format="gif -index 1"
        )

        self.style.element_create(
            "Search.field",
            "image",
            "search1",
            ("focus", "search2"),
            border=[22, 7, 14],
            sticky="ew",
        )

        self.style.layout(
            "Search.entry",
            [
                (
                    "Search.field",
                    {
                        "sticky": "nswe",
                        "border": 1,
                        "children": [
                            (
                                "Entry.padding",
                                {
                                    "sticky": "nswe",
                                    "children": [
                                        ("Entry.textarea", {"sticky": "nswe"})
                                    ],
                                },
                            )
                        ],
                    },
                )
            ],
        )
        self.style.configure("Search.entry")

        # frames
        fr_global = ttk.Frame(self, name="global")
        fr_search = ttk.Frame(self, name="search_form")

        # UI vars
        self.app_name = StringVar(fr_global, "Sample desktop form")
        self.app_total = StringVar(fr_global, "0")
        self.app_url = StringVar(fr_global, "http://isogeo-api-pysdk.readthedocs.io")
        self.app_results = StringVar(fr_search, "0")

        # -- WIDGETS CREATION -------------------------------------------------
        # add widgets
        lbl_app_name = tk.Label(fr_global, textvariable=self.app_name)
        lbl_app_total = ttk.Label(fr_global, textvariable=self.app_total)
        btn_app_url = ttk.Button(
            fr_global,
            text="APP Website",
            command=lambda: self.worker_allocator(
                async_loop=self.async_loop, to_do="open_web", **{"url": self.app_url}
            ),
        )

        lbl_actions = ttk.Label(fr_search, text="Linked action")
        lbl_contacts = ttk.Label(fr_search, text="Contact")
        lbl_formats = ttk.Label(fr_search, text="Source format")
        lbl_inspires = ttk.Label(fr_search, text="INSPIRE theme")
        lbl_keywords = ttk.Label(fr_search, text="Keyword")
        lbl_licenses = ttk.Label(fr_search, text="License")
        lbl_owners = ttk.Label(fr_search, text="Owner")
        lbl_shares = ttk.Label(fr_search, text="Share")
        lbl_srs = ttk.Label(fr_search, text="Source spatial reference system")
        lbl_types = ttk.Label(fr_search, text="Type")

        # add form widgets
        self.ent_search = AutocompleteEntry(
            fr_search, style="Search.entry", width=20, completevalues=list()
        )

        self.cb_actions = AutocompleteCombobox(fr_search)
        self.cb_contacts = AutocompleteCombobox(fr_search)
        self.cb_formats = AutocompleteCombobox(fr_search)
        self.cb_inspires = AutocompleteCombobox(fr_search)
        self.cb_keywords = AutocompleteCombobox(fr_search)
        self.cb_licenses = AutocompleteCombobox(fr_search)
        self.cb_owners = AutocompleteCombobox(fr_search)
        self.cb_shares = AutocompleteCombobox(fr_search)
        self.cb_srs = AutocompleteCombobox(fr_search)
        self.cb_types = AutocompleteCombobox(fr_search)

        lbl_results = ttk.Label(fr_search, textvariable=self.app_results)

        btn_reset = ttk.Button(
            master,
            text="Reset",
            command=lambda: self.worker_allocator(
                async_loop=self.async_loop, to_do="form_clear", **{"clear": 1}
            ),
        )
        btn_close = ttk.Button(master, text="Close", command=master.destroy)

        # after UI build
        self.worker_allocator(
            async_loop=self.async_loop, to_do="form_clear", **{"clear": 1}
        )

        # -- WIDGETS PLACEMENT ------------------------------------------------
        d_pad = {"padx": 5, "pady": 5, "sticky": "NSEW"}

        lbl_app_name.grid(row=0, column=0, **d_pad)
        btn_app_url.grid(row=1, column=0, **d_pad)
        lbl_app_total.grid(row=2, column=0, **d_pad)

        self.ent_search.grid(row=1, columnspan=3, **d_pad)

        self.cb_actions.grid(row=3, column=0, **d_pad)
        self.cb_contacts.grid(row=3, column=1, **d_pad)
        self.cb_formats.grid(row=3, column=2, **d_pad)
        self.cb_inspires.grid(row=5, column=0, **d_pad)
        self.cb_keywords.grid(row=5, column=1, **d_pad)
        self.cb_licenses.grid(row=5, column=2, **d_pad)
        self.cb_owners.grid(row=7, column=0, **d_pad)
        self.cb_shares.grid(row=7, column=1, **d_pad)
        self.cb_srs.grid(row=7, column=2, **d_pad)
        self.cb_types.grid(row=9, column=1, **d_pad)

        lbl_actions.grid(row=2, column=0, **d_pad)
        lbl_contacts.grid(row=2, column=1, **d_pad)
        lbl_formats.grid(row=2, column=2, **d_pad)
        lbl_inspires.grid(row=4, column=0, **d_pad)
        lbl_keywords.grid(row=4, column=1, **d_pad)
        lbl_licenses.grid(row=4, column=2, **d_pad)
        lbl_owners.grid(row=6, column=0, **d_pad)
        lbl_shares.grid(row=6, column=1, **d_pad)
        lbl_srs.grid(row=6, column=2, **d_pad)
        lbl_types.grid(row=8, column=1, **d_pad)

        lbl_results.grid(row=22, column=0, columnspan=2, **d_pad)

        fr_global.grid(row=0, columnspan=1, **d_pad)
        fr_search.grid(row=1, columnspan=1, **d_pad)

        btn_reset.grid(row=2, column=0, sticky="NSW", padx=5, pady=5)
        btn_close.grid(row=2, column=0, sticky="NSE", padx=5, pady=5)

        # connecting comboboxes event
        self.cb_actions.bind("<<ComboboxSelected>>", self.cbs_manager)
        self.cb_contacts.bind("<<ComboboxSelected>>", self.cbs_manager)
        self.cb_formats.bind("<<ComboboxSelected>>", self.cbs_manager)
        self.cb_inspires.bind("<<ComboboxSelected>>", self.cbs_manager)
        self.cb_keywords.bind("<<ComboboxSelected>>", self.cbs_manager)
        self.cb_licenses.bind("<<ComboboxSelected>>", self.cbs_manager)
        self.cb_owners.bind("<<ComboboxSelected>>", self.cbs_manager)
        self.cb_shares.bind("<<ComboboxSelected>>", self.cbs_manager)
        self.cb_srs.bind("<<ComboboxSelected>>", self.cbs_manager)
        self.cb_types.bind("<<ComboboxSelected>>", self.cbs_manager)

    # -- TASKS HUB ------------------------------------------------------------
    def cbs_manager(self, event):
        self.worker_allocator(
            async_loop=self.async_loop, to_do="form_update", **{"clear": 0}
        )

    def worker_allocator(self, async_loop, to_do, **kwargs):
        """ Handler starting the asyncio part. """
        d = kwargs
        threading.Thread(
            target=self._asyncio_thread, args=(async_loop, to_do, d)
        ).start()

    def _asyncio_thread(self, async_loop, to_do, kwargus):
        if to_do == "form_clear":
            async_loop.run_until_complete(self.fill_form(clear=1))
        elif to_do == "form_update":
            async_loop.run_until_complete(self.fill_form(clear=0))
        elif to_do == "open_web":
            async_loop.run_until_complete(self.open_url(kwargus.get("url").get()))
        else:
            pass

    # -- ASYNC METHODS --------------------------------------------------------
    async def open_url(self, url):
        open_new_tab(url)

    async def fill_form(self, clear=0):
        if not hasattr(self, "isogeo"):
            self._init_isogeo()
        else:
            logging.info("App is already connected to Isogeo API")
            pass

        # search
        if clear:
            # clear
            self.ent_search.delete(0, "end")
            self.cb_actions.set("")
            self.cb_contacts.set("")
            self.cb_formats.set("")
            self.cb_inspires.set("")
            self.cb_keywords.set("")
            self.cb_licenses.set("")
            self.cb_owners.set("")
            self.cb_shares.set("")
            self.cb_srs.set("")
            self.cb_types.set("")
            # new search
            search = self.isogeo.search(
                self.token, page_size=0, whole_share=0, augment=1, tags_as_dicts=1
            )
            app_total = results_total = search.get("total")
            self.app_total.set("Total: {} metadata".format(app_total))
        else:
            query = self.ent_search.get() + " "
            query += self.tags.get("actions").get(self.cb_actions.get(), "") + " "
            query += self.tags.get("contacts").get(self.cb_contacts.get(), "") + " "
            query += self.tags.get("formats").get(self.cb_formats.get(), "") + " "
            query += self.tags.get("inspires").get(self.cb_inspires.get(), "") + " "
            query += self.tags.get("keywords").get(self.cb_keywords.get(), "") + " "
            query += self.tags.get("licenses").get(self.cb_licenses.get(), "") + " "
            query += self.tags.get("owners").get(self.cb_owners.get(), "") + " "
            query += self.tags.get("shares").get(self.cb_shares.get(), "") + " "
            query += self.tags.get("srs").get(self.cb_srs.get(), "") + " "
            query += self.tags.get("types").get(self.cb_types.get(), "") + " "
            search = self.isogeo.search(
                self.token,
                page_size=0,
                whole_share=0,
                augment=1,
                tags_as_dicts=1,
                query=query,
            )
            results_total = search.get("total")
            logging.debug(search.get("query"))
        self.tags = search.get("tags")

        # set values
        self.app_results.set("Results count: {} metadata".format(results_total))
        self.ent_search.set_completion_list(list(self.tags.get("keywords").values()))
        self.cb_actions.set_completion_list(list(self.tags.get("actions")))
        self.cb_contacts.set_completion_list(list(self.tags.get("contacts")))
        self.cb_formats.set_completion_list(list(self.tags.get("formats")))
        self.cb_inspires.set_completion_list(list(self.tags.get("inspires")))
        self.cb_keywords.set_completion_list(list(self.tags.get("keywords")))
        self.cb_licenses.set_completion_list(list(self.tags.get("licenses")))
        self.cb_owners.set_completion_list(list(self.tags.get("owners")))
        self.cb_shares.set_completion_list(list(self.tags.get("shares")))
        self.cb_srs.set_completion_list(list(self.tags.get("srs")))
        self.cb_types.set_completion_list(list(self.tags.get("types")))

    def _init_isogeo(self):
        api_credentials = utils.credentials_loader("client_secrets.json")
        self.isogeo = Isogeo(
            client_id=api_credentials.get("client_id"),
            client_secret=api_credentials.get("client_secret"),
        )
        self.token = self.isogeo.connect()
        # app properties
        self.isogeo.get_app_properties(self.token)
        self.app_props = self.isogeo.app_properties
        self.app_name.set(
            "Authenticated application: {}".format(self.app_props.get("name"))
        )
        self.app_url.set(self.app_props.get("url", "https://www.isogeo.com"))