class Example(Frame): def __init__(self, master): Frame.__init__(self, master) self.dict = {'Asia': ['Japan', 'China', 'India'], 'Europe': ['Portugal', 'Switzerland', 'Ukraine']} self.var_a = StringVar(self) self.var_b = StringVar(self) self.var_a.trace('w', self.update_options) self.option_menu_a = OptionMenu(self, self.var_a, *self.dict.keys()) self.option_menu_a.pack(side="top") self.option_menu_a["width"] = 10 self.option_menu_b = OptionMenu(self, self.var_b, '') self.option_menu_b["width"] = 10 self.option_menu_b.pack(side="top") self.var_a.set('Asia') def update_options(self, *args): countries = self.dict[self.var_a.get()] self.var_b.set(countries[0]) menu = self.option_menu_b['menu'] menu.delete(0, 'end') for c in countries: menu.add_command(label=c, command=lambda x=c: self.var_b.set(x))
def update(self, motorControls): # wanneer er nieuwe aansturingen worden aangesloten # of een aansturing wordt verwijderd wordt hier het frame geupdate. if motorControls == self.motorControls: return for widget in self.widgets: widget.destroy() for control in motorControls: option = StringVar() subFrame = ttk.Frame(self.subFrame, style='My.TFrame') label = Label(subFrame, fg='black', bg='white', text=control.name) label.pack(fill=X) inrol_button = Button(subFrame, text="Inrollen", command=lambda: control.rollIn(option.get())) inrol_button.pack(fill=X) uitrol_button = Button(subFrame, text="Uitrollen", command=lambda: control.rollOut(option.get())) uitrol_button.pack(fill=X) stop_button = Button(subFrame, text="Onderbreek", command=control.stopRolling) stop_button.pack(fill=X) # optionMenu optionSubFrame = ttk.Frame(subFrame, style='My.TFrame') optionLabel = Label(optionSubFrame, fg='black', bg='white', text="Tot:") optionLabel.pack(side=LEFT) options = ["over 1 uur", "over 2 uur", "over 3 uur", "over 4 uur", "einde dag"] option.set(options[0]) optionMenu = OptionMenu(optionSubFrame, option, *options) optionMenu.config(width=10) optionMenu.pack(side=RIGHT) optionSubFrame.pack(fill=X) auto_button = Button(subFrame, text="Automatisch", command=lambda: control.setTimeout('auto')) auto_button.pack(fill=X) self.widgets.append(subFrame) subFrame.pack(padx=5, side=LEFT) self.motorControls = motorControls.copy()
class Example(Frame): def __init__(self, master): Frame.__init__(self, master) self.dict = { 'Asia': ['Japan', 'China', 'India'], 'Europe': ['Portugal', 'Switzerland', 'Ukraine'] } self.var_a = StringVar(self) self.var_b = StringVar(self) self.var_a.trace('w', self.update_options) self.option_menu_a = OptionMenu(self, self.var_a, *self.dict.keys()) self.option_menu_a.pack(side="top") self.option_menu_a["width"] = 10 self.option_menu_b = OptionMenu(self, self.var_b, '') self.option_menu_b["width"] = 10 self.option_menu_b.pack(side="top") self.var_a.set('Asia') def update_options(self, *args): countries = self.dict[self.var_a.get()] self.var_b.set(countries[0]) menu = self.option_menu_b['menu'] menu.delete(0, 'end') for c in countries: menu.add_command(label=c, command=lambda x=c: self.var_b.set(x))
def __init__(self, nb, motorControls): #hier wordt het homeframe gemaakt met de verschillende functionele knoppen voor het startscherm super().__init__(nb, "Home") self.motorControls = motorControls.copy() self.widgets = [] style = ttk.Style() style.configure('My.TFrame', background='white') # gui widgets voor het aansturen van alle schermen ter gelijke tijd self.subFrame = ttk.Frame(self, style='My.TFrame') subFrame = ttk.Frame(self.subFrame, style='My.TFrame') option = StringVar() label = Label(subFrame, fg='black', bg='white', text="Alle Schermen") label.pack(fill=X) inrol_button = Button(subFrame, text="Inrollen", command=lambda: self.rollIn(option.get())) inrol_button.pack(fill=X) uitrol_button = Button(subFrame, text="Uitrollen", command=lambda: self.rollOut(option.get())) uitrol_button.pack(fill=X) stop_button = Button(subFrame, text="Onderbreek", command=self.stopRolling) stop_button.pack(fill=X) # optionMenu optionSubFrame = ttk.Frame(subFrame, style='My.TFrame') optionLabel = Label(optionSubFrame, fg='black', bg='white', text="Tot:") optionLabel.pack(side=LEFT) options = ["over 1 uur", "over 2 uur", "over 3 uur", "over 4 uur", "einde dag"] option.set(options[0]) optionMenu = OptionMenu(optionSubFrame, option, *options) optionMenu.config(width=10) optionMenu.pack(side=RIGHT) optionSubFrame.pack(fill=X) auto_button = Button(subFrame, text="Automatisch", command=self.automatic) auto_button.pack(fill=X) subFrame.pack(padx=5, side=LEFT) self.subFrame.place(relx=0.5, rely=0.5, anchor=CENTER)
class PlayerSelectionView: HUMAN = 'Human' RANDOM = 'Random' SMART_RANDOM = 'Smart Random' BOARD_HEURISTIC = 'Consecutive Pieces Heuristic' MOVE_HEURISTIC = 'Num Wins Heuristic' PLAYER_TYPES = [ BOARD_HEURISTIC, MOVE_HEURISTIC, HUMAN, RANDOM, SMART_RANDOM ] def __init__(self, window: Tk, color): self.window = window self.color = color self.player_selection = StringVar(window) self.player_selection.set(self.PLAYER_TYPES[0]) self.selection_frame = Frame(window) text = ('Red' if color == Agent.RED_PLAYER else 'Black') + ' Player: ' self.name_label = Label(self.selection_frame, text=text) self.name_label.pack(side=LEFT) self.option_menu = OptionMenu(self.selection_frame, self.player_selection, *self.PLAYER_TYPES) self.option_menu.pack(side=LEFT) self.selection_frame.pack() def get_player_from_selection(self): return self.player_selection.get() def get_color(self): return self.color
def body(self, master): frm_base = Frame(master) frm_base.pack(fill=BOTH) options = [ "Date", "Amount", "Account Name", "Category Name", "Description" ] self.__sort_by.set(options[0]) op = OptionMenu(frm_base, self.__sort_by, *options) op.pack(padx=5, pady=5) op.configure(relief=GROOVE, width="25", height="2", bg=DATA_COLOR, font=DATA_FONT, fg=DATA_FONT_COLOR) order = ["Ascending", "Descending"] self.__order.set(order[0]) op = OptionMenu(frm_base, self.__order, *order) op.pack(padx=5, pady=5) op.configure(relief=GROOVE, width="25", height="2", bg=DATA_COLOR, font=DATA_FONT, fg=DATA_FONT_COLOR) frm_date = Frame(frm_base) frm_date.pack() return frm_base
def __init__(self, master, file_number: int): super().__init__(master) self.file_number = file_number self.frame = Frame(self.master) self.frame.pack() self.title = Label(self.frame, text='Select the files') self.title.pack() self.selected_file_names = [] for i in range(self.file_number): selected_file = StringVar(master) selected_file.set("-") available_tracks = ["-"] + list(workspace.keys()) file_selector = OptionMenu(self.frame, selected_file, *available_tracks, command=self.on_file_select(i)) file_selector.pack() self.selected_file_names.append(selected_file) self.body = Frame(self.frame) self.body.pack() self.error_message = Label(self, text="Select the files") self.submit = Button(self.frame, text='подтвердить', state='disabled', command=self.on_submit) self.submit.pack() self.selected_tracks = [None] * file_number
class GuiGeneratorSelect(Frame): def __init__(self, parent, generators): Frame.__init__(self, parent) self.parent = parent self.pack() self._generators = generators self._generatorName = StringVar() self._generatorName.set(generators[0].getName()) self._generatorName.trace("w", self._switchSettings) self._generatorLbl = Label(self, text="Generator"); self._generatorLbl.pack(side=LEFT) param = (self, self._generatorName) + tuple(i.getName() for i in generators) self._generatorOpt = OptionMenu(*param) self._generatorOpt.pack(side=LEFT) self._switchSettings() def _switchSettings(self, *args): print("DBG: switch generator settings") for i in self._generators: if i.getName() == self._generatorName.get(): i.pack() self._generatorGui = i print("pack " + str(i.getName())) else: i.pack_forget() print("unpack " + str(i.getName())) def getCurrGeneratorGui(self): return self._generatorGui
class Select(Frame): def __init__(self, master=None, labelText='', options=[], width=30): ''' Create a selector with label :param master: Frame, frame :param labelText: Frame, label texte :param options: Array, Frame options :param width: Int, label with ''' Frame.__init__(self, master) self.pack() self.options = options self.label = Label(self, anchor=W, text=labelText, width=width) self.label.pack(side='left') self.var = StringVar() self.var.set(list(self.options.keys())[0]) self.select = OptionMenu(self, self.var, *self.options.keys()) self.select.pack(side='right') def setEvent(self, event): self.var.trace("w", event) def get(self): return self.options[self.var.get()] def setValue(self, value): self.var.set(value)
def build_gui(self): padding = 5 lbl = Label(self.top, text='Difficulty:') lbl.pack() difficulty_types = [ setting['name'] for setting in settings.storage['difficulty'] ] self.current_difficulty = StringVar(self.top) self.current_difficulty.set(settings.storage['default_difficulty']) difficultyLevel = OptionMenu(self.top, self.current_difficulty, *difficulty_types, command=self.option_select) difficultyLevel.pack() self.tvw = ttk.Treeview(self.top) self.tvw['columns'] = ('Name', 'Time', 'Date') self.tvw.column('#0', width=0, stretch=NO) self.tvw.column('Name', anchor=CENTER, width=80) self.tvw.column('Time', anchor=CENTER, width=80) self.tvw.column('Date', anchor=CENTER, width=80) self.tvw.heading('#0', text='', anchor=CENTER) self.tvw.heading('Name', text='Name', anchor=CENTER) self.tvw.heading('Time', text='Time', anchor=CENTER) self.tvw.heading('Date', text='Date', anchor=CENTER) self.populate_list() self.tvw.pack() closeButton = Button(self.top, text='OK', command=self.ok) closeButton.pack(padx=padding, pady=padding)
class PVmodule_tk(Frame): """ classdocs """ def __init__(self, pvapp, top): """ Constructor """ self.pvapp = pvapp Frame.__init__(self, top) self.pack(expand=True) # if user resizes, expand Frame self.pack(fill='both') self.focus_set() # get the focus self.grab_set() # make this window modal self['bg'] = 'black' # set black background self['padx'] = '15' # pad sides with 15 points self['pady'] = '5' # pad top/bottom 5 points self.master.title('PVmodule') # set title bar self.SPlogoLabel = Label(self, image=self.pvapp.SPlogo, cnf={'borderwidth': '0'}) self.SPlogoLabel.pack({'side': 'top'}) self.numberCells = IntVar(self) # bind numberCells self.numberCells.set(MODULE_SIZES[0]) # default value # pylint: disable = W0142 self.numberCellsOption = OptionMenu(self, self.numberCells, *MODULE_SIZES) # pylint: enable = W0142 self.numberCellsOption.pack({'side': 'top', 'fill': 'both'}) self.QUIT = Button(self, cnf={'text': 'Quit', 'command': self.quit}) self.QUIT.pack({'side': 'top', 'fill': 'both'})
class LabelMenu(Frame): def __init__(self, parent, width=400, height=50, text="Menu", val={"item#1":1, "item#2":2}, font=('Times', 12), ratio=0.5): Frame.__init__(self, parent, width=width, height=height) self.pack_propagate(0) self.f1 = Frame(self, width=int(width*ratio), height=height) self.f1.pack_propagate(0) self.f1.pack(side='left') self.f2 = Frame(self, width=int(width*(1-ratio)), height=height) self.f2.pack_propagate(0) self.f2.pack(side='left') self.lb = Label(self.f1, text=text, font=font) self.lb.pack(fill='both', expand=True) self.dic = {str(i):val[i] for i in val} self.opt = [i for i in self.dic] self.var = StringVar(self) self.var.set(self.opt[0]) print(self.opt) self.mn = OptionMenu(self.f2, self.var, *self.opt) self.mn.pack(fill='both', expand=True) def get(self): return self.dic[self.var.get()]
class SortableCharacterMenu: src_char_list = [ "Alex", "Ryu", "Yun", "Dudley", "Necro", "Hugo", "Ibuki", "Elena", "Oro", "Yang", "Ken", "Sean", "Urien", "Gouki", "Shin Gouki", "Chun Li", "Makoto", "Q", "Twelve", "Remy" ] abc_char_list = sorted(src_char_list, key=str.lower) def __init__(self, tk_root, char_list_str): self.tk_root = tk_root self.char_list_str = char_list_str self.tk_menu = None self.sort_src() def _create_and_repack_menu(self, char_list): if self.tk_menu: self.tk_menu.pack_forget() self.tk_menu = OptionMenu(self.tk_root, self.char_list_str, *char_list, command=updateFrameColor) self.tk_menu.config(width=10, bd=1) self.tk_menu.pack() def sort_abc(self): self._create_and_repack_menu(self.abc_char_list) def sort_src(self): self._create_and_repack_menu(self.src_char_list)
def _init_corpus_select(self, parent): innerframe = Frame(parent, background=self._BACKGROUND_COLOUR) self.var = StringVar(innerframe) self.var.set(self.model.DEFAULT_CORPUS) Label( innerframe, justify=LEFT, text=" Corpus: ", background=self._BACKGROUND_COLOUR, padx=2, pady=1, border=0, ).pack(side="left") other_corpora = list(self.model.CORPORA.keys()).remove( self.model.DEFAULT_CORPUS) om = OptionMenu(innerframe, self.var, self.model.DEFAULT_CORPUS, command=self.corpus_selected, *self.model.non_default_corpora()) om["borderwidth"] = 0 om["highlightthickness"] = 1 om.pack(side="left") innerframe.pack(side="top", fill="x", anchor="n")
def create_selection_menu(self, cb_on_select, *opts, always_trigger_onselect=False, no_destructure=False, pass_selection_to_callback=False): """ Quick way of creating a drop-down menu with a set of options and selection callbacks. :param cb_on_select: Menu item selection event callback :param opts: Menu options. These should be a list of two-element tuples where the first item is the label and the second is the corresponding value :param always_trigger_onselect: Whether the selection callback should be triggered even if an already-selected item was selected :param no_destructure: Whether option values should be destructured into the arguments of the callback :param pass_selection_to_callback: Whether or not to pass the selected value to the selection callback function :return: Getter function for the currently selected `value` (not label) """ options_dict = dict() selection_active = StringVar(self.root) selection_previous = StringVar(self.root) for (key, value) in opts: options_dict[key] = value menu = OptionMenu(self.options_frame, selection_active, *options_dict.keys()) def on_select(*args): """ Callback function for when a menu item is selected :param args: Ignored arguments. Just contains the modified variable :return: None """ # Check if a previously un-selected item was selected (or if the event should be processed anyway) if selection_active.get() != selection_previous.get() or always_trigger_onselect: selection_previous.set(selection_active.get()) # Call callback if one was specified if cb_on_select: if pass_selection_to_callback: # Attempt to destructure parameter as much as possible # This is just a lazy way of passing sets of arguments in less LOC if (not no_destructure) and dir(options_dict[selection_active.get()]).__contains__("__iter__"): if type(options_dict[selection_active.get()]) is dict: cb_on_select(**options_dict[selection_active.get()]) else: cb_on_select(*(options_dict[selection_active.get()])) else: cb_on_select(options_dict[selection_active.get()]) else: cb_on_select() # Set a callback for when variable changes value selection_active.trace("w", on_select) # Pack menu if a side as packed, else assume packing will be done elsewhere menu.pack(side="left") # Select a menu option. This also triggers an initial callback selection_active.set(opts[0][0]) # Return a getter function to the active *value* (not key) return lambda: options_dict[selection_active.get()]
def create_select_month_option_menu(self): months = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'] self.clicked_month.set(months[0]) self.clicked_month.trace("w", self.callback) type_label = Label(self, text="Month") type_label.pack() dropdown = OptionMenu(self, self.clicked_month, *months) dropdown.pack()
class UserChoiceFrame(tk.Frame): def __init__(self, master=None, **kwargs): tk.Frame.__init__(self, master, **kwargs) # Option Box Actions self.options = [ "Please Select an Option", "Read Public DataBase", "Write To Public DataBase" ] self.var_select = StringVar(master) self.ovar = StringVar(master) self.ovar.set(self.options[0]) self.sideWindow = tk.Frame() self.obox = OptionMenu(master, self.ovar, *self.options, command=self.set_dropdown_value) self.obox.pack() self.close_button = tk.Button(self, text="Exit", command=self.exit_prog) self.close_button.pack(side=tk.BOTTOM) self.testbutton = tk.Button(self, text="Launch Selection", command=self.execute_dropdown_action) self.testbutton.pack() def set_dropdown_value(self, value): self.var_select = value def get_dropdown_value(self): return self.var_select def execute_dropdown_action(self): action = self.get_dropdown_value() if action == self.options[1]: # Action 1 : Read Public MessageBoard self.master.srv_rd_req_pub() self.disp_rd_txt_win() elif action == self.options[2]: # Action 2: Write to Public MessageBoard self.disp_wrt_txt_win() def disp_rd_txt_win(self): # Load text box into model self.master.gen_txt_frame(RdTextFrame) def disp_wrt_txt_win(self): # Load text box into model self.master.gen_txt_frame(WriteTextFrame) def exit_prog(self): self.master.close_connection() self.quit()
def front_page(open_project_page: object) -> None: """Creates the tkinter widgets and provides functions for the front page Args: open_project_page (function): Function opening the next project page """ all_projects = project.get_projects() # Create the load project widgets load_project_label = Label(root, text='Load a Project') load_project_label.pack() selected_project = StringVar(root) selected_project.set('--') # default value selected_project_menu = OptionMenu(root, selected_project, *all_projects) selected_project_menu.pack() load_button = Button( root, text="Load", command=lambda: [load_project(), destroy_main_page(), open_project_page()]) load_button.pack() # Create the new project widgets new_project_label = Label(root, text='Start A New Project') new_project_label.pack() new_project_button = Button( root, text="New Project", command=lambda: [new_project(), destroy_main_page()]) new_project_button.pack() def destroy_main_page() -> None: """Destroy all widgets from the main page """ load_button.destroy() selected_project_menu.destroy() load_project_label.destroy() new_project_button.destroy() new_project_label.destroy() def new_project() -> None: # TODO: Setup new project prompts and filedialog.askdirectory pass def load_project() -> None: """Load the project information into the project object and display the project data """ project.load_project(selected_project.get()) load_project_label = Label(root, text=project.get_project_data()) load_project_label.pack()
class Loadlist(): def __init__(self, master): self.master = master self.master.geometry("250x100") self.master.title("Load List") self.master.resizable(False, False) self.menu = Menu(self.master) self.file_menu = Menu(self.menu, tearoff=0) self.file_menu.add_command(label="Load", accelerator='Ctrl+L', command=self.load) self.file_menu.add_command(label="Exit", accelerator='Alt+F4', command=self.exitmenu) self.menu.add_cascade(label="File", menu=self.file_menu) self.about_menu = Menu(self.menu, tearoff=0) self.about_menu.add_command(label="About", accelerator='Ctrl+I', command=about_menu) self.menu.add_cascade(label="About", menu=self.about_menu) self.help_menu = Menu(self.menu, tearoff=0) self.help_menu.add_command(label="Help", accelerator='Alt+F1', command=self.helpmenu) self.menu.add_cascade(label="Help", menu=self.help_menu) self.master.config(menu=self.menu) self.master.bind('<Control-l>', lambda event: self.load()) self.master.bind('<Alt-F4>', lambda event: self.exitmenu()) self.master.bind('<Control-F1>', lambda event: self.helpmenu()) self.master.bind('<Control-i>', lambda event: about_menu()) global flist f = os.listdir() if not f: msg.showerror("ERROR", "THERE IS NO ROUTINE") self.master.destroy() else: flist = StringVar(master) flist.set(f[0]) self.chomenu = OptionMenu(self.master, flist, *f) self.chomenu.pack() self.loadb = Button(self.master, text="LOAD", command=self.load) self.loadb.pack() def exitmenu(self): """ exit menu function """ if msg.askokcancel("Quit?", "Really quit?"): self.master.destroy() def helpmenu(self): msg.showinfo("Help", "Here you can choose the routine you want to load") def load(self): msg.showinfo("SUCCESS", "TO DO SUCCESSFULLY LOADED") root5 = Toplevel() Loader(root5)
def add_side_field(self, master, edge_settings, side): side_var = StringVar(master) side_var.set(side) Label(master, text='Side:', padx=5).pack(side=LEFT) side_entry = OptionMenu(master, side_var, "top", "right", "bottom", "left") side_entry.pack(side=LEFT) edge_settings['side'] = side_var
def change_level(self): ''' change the level should press the button confirm to change the level and start a game in that level ''' level= ("beginner","intermediate","advanced") self.choices=StringVar(self.__parent) self.choices.set(self.level) options=OptionMenu(self,self.choices,*level,command=self.confirm) options.pack()
def body(self, master): frm_base = Frame(master) frm_base.pack(fill=BOTH) Label(frm_base, height="2", width="30", text="Category:", bg=BUTTON_COLOR, font=BUTTON_FONT, fg=BUTTON_FONT_COLOR).pack(padx=5, pady=5) self.__category.set(self.__categories[0]) op = OptionMenu(frm_base, self.__category, *self.__categories) op.pack(padx=5, pady=5) op.configure(relief=GROOVE, width="25", height="2", bg=DATA_COLOR, font=DATA_FONT, fg=DATA_FONT_COLOR) return frm_base
def __init__(self, controller, title: str, label: str, values: Optional[Dict] = None, buttons: Optional[Dict] = None): if values is None: values = {} if buttons is None: buttons = {"ok": {}, "cancel": {}} super().__init__(controller, title, label, buttons, allow_exit=False) self.values = values self.entry_frame = Frame(self.top, bg=self.tk_format.bg) self.entry_frame.pack(pady=(10, 20)) self.labels = {} self.entries = {} self.mins = {} self.maxes = {} for val in values: frame = Frame(self.entry_frame, bg=self.tk_format.bg) frame.pack(pady=(5, 5)) self.labels[val] = Label(frame, text="{0:>15}".format(val) + ": ", fg=self.tk_format.textcolor, bg=self.tk_format.bg) self.labels[val].pack(side=LEFT, padx=(3, 3)) if val != "Tray position": self.entries[val] = Entry( frame, bg=self.tk_format.entry_background, selectbackground=self.tk_format.selectbackground, selectforeground=self.tk_format.selectforeground, ) self.entries[val].pack(side=LEFT) else: self.entries[val] = StringVar() self.entries[val].set("White reference") print(self.entries["Tray position"].get()) menu = OptionMenu( frame, self.entries[val], "{0:15}".format("White reference"), "{0:18}".format("1"), "2 ", "3 ", "4 ", "5 ", ) menu.configure(width=15, highlightbackground=self.tk_format. highlightbackgroundcolor) menu.pack() self.set_buttons(buttons)
class MonthOptionMenu(Frame): langs = { "eng": [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], "pt-br": [ "Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro" ] } def __init__(self, master, *args, lang="eng", **kwargs): super(MonthOptionMenu, self).__init__(master, *args, **kwargs) self.create_optionmenu() self.lang = lang self.set_lang(self.lang) def create_optionmenu(self): from tkinter import StringVar, IntVar, OptionMenu, Label self.label = Label(self, text="Month", width=LABEL_WIDTH) self.string_optionmenu = StringVar() self.optionmenu = OptionMenu(self, self.string_optionmenu, []) self.label.pack(side="left") self.optionmenu.pack(side="left", fill="x", expand=True) def set_lang(self, lang): if lang in self.langs: self.lang = lang values = self.langs[lang] self.optionmenu.children["menu"].delete(0, "end") self.string_optionmenu.set(values[0]) for value in values: self.optionmenu.children["menu"].add_command( label=value, command=lambda string=value: self.string_optionmenu.set( string)) def set_value(self, value): if isinstance(value, int) and 0 < value <= len(self.langs[self.lang]): month = self.langs[self.lang][value - 1] self.string_optionmenu.set(month) elif isinstance(value, str) and value.isdigit(): self.set_value(int(value)) def get_value(self): return list(self.langs[self.lang]).index( self.string_optionmenu.get()) + 1 def set_label(self, label): self.label.config(text=label)
class DropDown(GuiWidget): def setup(self, master, items, *args, **kwargs): # Stores current selection self.selection = StringVar(master) self.selection.set(items[0]) # The menu widget self.popupMenu = OptionMenu(master, self.selection, *items) self.popupMenu.pack() def __str__(self): return str(self.selection.get())
def _init_corpus_select(self, parent): innerframe = Frame(parent, background=self._BACKGROUND_COLOUR) self.var = StringVar(innerframe) self.var.set(self.model.DEFAULT_CORPUS) Label(innerframe, justify=LEFT, text=' Corpus: ', background=self._BACKGROUND_COLOUR, padx = 2, pady = 1, border = 0).pack(side='left') other_corpora = list(self.model.CORPORA.keys()).remove(self.model.DEFAULT_CORPUS) om = OptionMenu(innerframe, self.var, self.model.DEFAULT_CORPUS, command=self.corpus_selected, *self.model.non_default_corpora()) om['borderwidth'] = 0 om['highlightthickness'] = 1 om.pack(side='left') innerframe.pack(side='top', fill='x', anchor='n')
def input(self): # vcmd = (self.register(self.onValidate), '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W') # self.bootstrap = IntVar(self, value="1000") # self.entry = Entry(self.labelFrameBootstrap, validate="key", validatecommand=vcmd, textvariable=self.bootstrap) # self.bootstrap = max(self.bootstrap.get(), 1000) # self.entry.grid(column=1, row=1, padx=30, pady=10) # self.entry.pack() self.bootstrap = IntVar(self.labelFrameBootstrap) self.bootstrap.set(next(iter(BOOTSTRAP_QUANTITY))) w = OptionMenu(self.labelFrameBootstrap, self.bootstrap, *BOOTSTRAP_QUANTITY) w.pack()
def dropdown_option(type, option_name, row, column): if type == 'cosmetic': option = cosmetic_options[option_name] elif type == 'sfx': option = sfx_options[option_name] optionFrame = Frame(romSettingsFrame) optionFrame.grid(row=row, column=column, sticky=E) optionLabel = Label(optionFrame, text=option.display_name) optionLabel.pack(side=LEFT) setattr(opts, option_name, StringVar()) getattr(opts, option_name).set(option.name_lookup[option.default]) optionMenu = OptionMenu(optionFrame, getattr(opts, option_name), *option.name_lookup.values()) optionMenu.pack(side=LEFT)
def createWidgets(self): self.sayHi = tk.Button(self) self.sayHi["text"] = "Eds Button" self.sayHi["command"] = self.say_Hello self.sayHi.pack(side="bottom") for option in options: f = Frame(self) f.pack(side="bottom") Label(f, text=option).pack(side="left") v = StringVar(self) o = OptionMenu(f, v, *options.get(option).values()) o.pack(side="right") self.options[option] = v
def __init__(self, master): self.G = None ttk.Frame.__init__(self, master) #----MENU ----# self.menu = Frame(self) self.menu.grid(row=0, column=0, sticky='nsew', rowspan=2) #--------Boton para cargar Gramatica ----# btnCargar = Button(self.menu, text='Cargar gramatica') btnCargar.config(command=lambda: self.cargarGram()) btnCargar.pack(fill='x') #--------Tipo de gramatica ----# self.gramType = StringVar(self.menu) self.gramType.set('LL0') olGramType = OptionMenu(self.menu, self.gramType, *{'LL0', 'LL1'}) olGramType.pack(fill='x') #--------Analizar cadena ----# lblAnalizar = Label(self.menu, text='Cadena a analizar') lblAnalizar.pack(fill='x') self.txtCadena = Entry(self.menu, width=4) self.txtCadena.pack(fill='x') self.btnAnalizar = Button(self.menu, text='Analizar cadena') self.btnAnalizar.config(state='disabled', command=lambda: self.analizar()) self.btnAnalizar.pack(fill='x') #----INFO ----# self.info = Frame(self, bg='white') self.info.grid(row=0, column=1, sticky='nsew') lblTituloGram = Label(self.info, text='Informacion de la gramatica', font=DEFAULTFONT, justify='center', bg='white') lblTituloGram.grid(row=0) self.lblinfoGram = Label(self.info, text='', justify='left', font=DEFAULTFONT, bg='white') self.lblinfoGram.grid(row=1, column=0, sticky='nsew') Label(self.info, text='Analisis', justify='left', font=DEFAULTFONT, bg='white').grid(row=0, column=2, sticky='nsew') self.lblanalisis = Label(self.info, text='', justify='left', font=DEFAULTFONT, bg='white') self.lblanalisis.grid(row=1, column=2, sticky='nsew')
def classSelection(self, C): classSelection = [] for i in self.classes: classSelection.append(i['name']) tk.Label(C, text="Choose a Class").place(relx=0.02, rely=0.08) self.classVar = tk.StringVar(C) self.classVar.set(classSelection[0]) classMenu = OptionMenu(C, self.classVar, classSelection[0], *classSelection[1:], command=self.infoBoxPop) classMenu.pack() classMenu.place(relx=0.01, rely=0.1, width=130, height=30)
def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.Obj_Menu_Create_Team = controller self.container = controller.container tk.Label(self, text="ASSOCIER UNE ÉQUIPE À UN BUZZER").pack() tk.Label( self, text= "(L'ordre dans lequel les buzzers sont(0,1,2...),correspondra à l'ordre dans lequel vous avez appuyé les touches.)" ).pack() tk.Label(self, text="Buzzers:").place(x=70, y=70) longueur_y = 115 self.list_variable_team = {} for n in range(0, (len(controller.list_team))): nom_buzz = "Buzz0{}".format(str(n)) tk.Label(self, text=nom_buzz).place(x=45, y=longueur_y) variable_team = StringVar(self) variable_team.set(controller.list_team[n]) # default value self.list_variable_team[n] = variable_team drop_down_menu_team = OptionMenu(self, variable_team, *controller.list_team) drop_down_menu_team.pack() drop_down_menu_team.place(x=100, y=longueur_y) longueur_y += 55 longueur_y += 30 btn_liste_equipe = Button(self, text="Liste des équipes", command=controller.show_team) btn_liste_equipe.place(x=100, y=longueur_y) longueur_y += 38 btn_revenir_menu = Button(self, text="revenir au menu principal", command=lambda: controller.switch_frame( controller.container, "Menu_Create_Team", controller=self.Obj_Menu_Create_Team)) btn_revenir_menu.place(x=100, y=longueur_y) longueur_y += 38 btn_jeu = Button( self, text="commencer le jeu", command=lambda: controller.switch_frame( controller.container, "Window_Detect_Winner", controller=self)) btn_jeu.place(x=100, y=longueur_y)
from tkinter import Tk, StringVar, OptionMenu, Button import sys OPTIONS = sys.argv[1].split("|") root = Tk() variable = StringVar(root) variable.set(OPTIONS[0]) # default value w = OptionMenu(root, variable, *OPTIONS) w.pack() def ok(): sys.stdout.write(variable.get()) sys.stdout.flush() root.destroy() button = Button(root, text="OK", command=ok) button.pack() root.mainloop()
class Masfir(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self._initUI() def _initUI(self): """ Initialise the UI """ self.parent.title("Masfir v0.1") self.style = Style() self.style.theme_use("default") self.pack(fill=BOTH, expand=1) self._createMenu() self._createUIElements() def _createMenu(self): """ Create the menu """ menubar = Menu(self.parent) self.parent.config(menu=menubar) # File Menu mnuFile = Menu(menubar) mnuFile.add_command(label="Exit", underline=1, command=self._onMenuFileExit) menubar.add_cascade(label="File", underline=0, menu=mnuFile) # Help Menu mnuHelp = Menu(menubar) mnuHelp.add_command(label="About", underline=0, command=self._onMenuHelpAbout) menubar.add_cascade(label="Help", underline=0, menu=mnuHelp) def _createUIElements(self): """ Create the main frame's UI elements """ # Top frame with the Load Directory controls frmLoadDir = Frame(self) frmLoadDir.pack(side=TOP, anchor=N, fill=X) self.sLoadDirVar = StringVar() lblLoadDir = Label(frmLoadDir, text="<Empty Directory>", textvariable=self.sLoadDirVar) lblLoadDir.pack(side=LEFT) btnLoadDir = Button(frmLoadDir, text="Load Directory", command=self._onBtnLoadDir) btnLoadDir.pack(side=RIGHT) # Dropdown with list of series (directories) detected frmSeriesSelector = Frame(self) frmSeriesSelector.pack(side=TOP, anchor=N, fill=X) self.sSeriesVar = StringVar() self.optSeries = OptionMenu(frmSeriesSelector, self.sSeriesVar, 'one', 'two', 'three', 'Loading', command=self._onBtnSeriesSelected) self.optSeries.pack(side=LEFT) # The two diff-style listboxes containing original and new episode list names frmListBoxes = Frame(self) frmListBoxes.pack(fill=BOTH, expand=1) self.lstOrgFiles = Listbox(frmListBoxes) self.lstOrgFiles.bind("<<ListboxSelect>>", self._onListOrgFiles) self.lstOrgFiles.pack(side=LEFT, fill=BOTH, expand=1, anchor=W) self.lstNewFiles = Listbox(frmListBoxes) self.lstNewFiles.bind("<<ListboxSelect>>", self._onListNewFiles) self.lstNewFiles.pack(side=RIGHT, fill=BOTH, expand=1, anchor=E) # Bottom buttons frmFinal = Frame(self) frmFinal.pack(side=BOTTOM, anchor=S, fill=X) btnRename = Button(frmFinal, text="Rename", command=self._onBtnRename) btnRename.pack(side=LEFT) btnExit = Button(frmFinal, text="Exit", command=self._onBtnExit) btnExit.pack(side=RIGHT) def _onBtnLoadDir(self): selectedDirectory = filedialog.askdirectory() self.optSeries['menu'].delete(0, END) # self.optSeries['menu'].insert('one', 'two', 'three') self.sSeriesVar.set('two') self.sLoadDirVar.set(selectedDirectory) # Populate listbox self.lstOrgFiles.delete(0, END) for item in os.listdir(selectedDirectory): self.lstOrgFiles.insert(END, item) def _onBtnExit(self): self._exit() def _onListOrgFiles(self): pass def _onListNewFiles(self): pass def _onBtnSeriesSelected(self): pass def _onBtnRename(self): pass def _onMenuFileExit(self): """ Jump to _exit() if Exit is clicked """ self._exit() def _onMenuHelpAbout(self): """ Something here """ pass def _exit(self): """ Exit the app """ self.quit()
class Frontend(): def __init__(self,x,y,b): self.x=str(x) #1600 self.y=str(y) #900 self.pressed=0 self.b=10 self.c=30 self.grapher=0 self.graph=[0,0,0,0] self.root=b def startwindow(self): # self.root=Tk() a=str(self.x+'x'+self.y) self.root.title('Wahrscheinlichkeinten & Simulation') self.root.geometry(a) self.g=Label(self.root,bg='white') self.g.place(x=0,y=0,width=self.x,height=self.y) # self.g.bind('<1>',self.optioncanged) self.lst1 = ['Marriage','Atom','BubbleGum','House_of_Cards','Lotto','SecretSanta','Coins'] self.var1 = StringVar(self.root) self.var1.set('Marriage') self.drop = OptionMenu(self.root,self.var1,*self.lst1) self.drop.config(font=('Arial',(30)),bg='white') self.drop['menu'].config(font=('calibri',(20)),bg='white') self.drop.pack(side=TOP) self.photo = PhotoImage(file='z1.gif') self.label = Label(image=self.photo,borderwidth=0) self.label.image = self.photo self.label.bind('<1>',self.MouseOneDown) self.label.place(y=0,x=int(self.x)-200) self.startbutton=Button(self.root,text='Start',font=('Arial',40),bg='#B4045F',borderwidth=5,command=self.startpressed) self.startbutton.place(x=0,y=int(self.y)-100,width=int(self.y)-200,height=100) self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='green',borderwidth=5,command=self.csvpressed) self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100) def startpressed(self): if self.grapher==1: for x in range(len(self.graph)): if self.graph[x]!=0: self.graph[x].destroy() self.grapher=0 self.root.update() a=self.var1.get() if self.pressed==1: try: self.b=int(self.changer0.get('1.0','end-1c')) except (AttributeError,TclError,ValueError): self.b=10 try: self.c=self.changer2.get('1.0','end-1c') except (AttributeError,TclError,ValueError): self.c=1 if a=='Marriage': self.run0=Marriage(self.b) self.run0.DEBUG=False self.run0.sim() elif a=='Atom': self.c=float(self.c) self.run1=Atom(self.c,self.b) self.run1.DEBUG=False self.run1.sim() elif a=='BubbleGum': self.run2=BubbleGum(self.b) self.run2.DEBUG=False self.run2.sim() self.grapher=1 self.graph=[0,0] g=str(round(self.run2.getrel()[0],4)) h=str(round(self.run2.getrel()[1],4)) self.graph[0]=Label(self.root,bg='white',text='Durchschnitt Karten zu viel: '+g,font=('calibri',19)) self.graph[0].place(x=10,y=450) self.graph[1]=Label(self.root,bg='white',text='Durchschnitt dass es passiert: '+h,font=('calibri',19)) self.graph[1].place(x=10,y=500) elif a=='House_of_Cards': if self.c=='': self.c=0 else: self.c=int(self.c) self.run3=House_of_Cards(self.b,self.c) self.run3.DEBUG=False self.run3.sim() self.grapher=1 self.graph=[0] self.graph[0]=Label(self.root,bg='white',text=('Durchschnitt: '+str(round(self.run3.getrel(),4))),font=('calibri',19)) self.graph[0].place(x=10,y=450) elif a=='Lotto': self.run4=Lotto(self.b) self.run4.DEBUG=False self.run4.sim() x=4 y=1 count=0 self.graph=[0,0,0,0] self.grapher=1 self.graph[0]=Label(self.root,bg='black') self.graph[0].place(x=10,width=10+(int(self.x)*0.8),height=1,y=int(self.y)-int(self.y)/4*0.5-350) self.graph[1]=Label(self.root,text='50%',bg='white',font=('calibri',10)) self.graph[1].place(x=60+(int(self.x)*0.8),width=50,height=50,y=int(self.y)-int(self.y)/4*0.5-375) self.graph[2]=Label(self.root,bg='black') self.graph[2].place(x=10,width=20,height=1,y=int(self.y)-350) self.graph[3]=Label(self.root,bg='black') self.graph[3].place(x=10,width=20,height=1,y=int(self.y)-int(self.y)/4-350) for draw in self.run4.turns: if draw.count(0) == 0: count += 1 elif draw.count(1) == 0: count += 1 elif draw.count(2) == 0: count += 1 elif draw.count(3) == 0: count += 1 elif draw.count(4) == 0: count += 1 elif draw.count(5) == 0: count += 1 self.graph+=[0] self.graph[x]=Label(self.root,bg='red') if str(self.c)=='1': self.graph[x].place(x=int(10+(int(self.x)*0.8)*((y-1)/self.b)),width=int(1250/self.b),height=int(self.y)-350-(int(int(self.y)-int(self.y)/4*(count/y)-350)),y=int(int(self.y)-int(self.y)/4*(count/y)-350)) else: self.graph[x].place(x=int(10+(int(self.x)*0.8)*(y/self.b)),width=3,height=3,y=int(int(self.y)-int(self.y)/4*(count/y)-350)) x+=1 y+=1 self.root.update() elif a=='SecretSanta': if self.c=='': self.c=1 else: self.c=int(self.c) self.run5=SecretSanta(self.b,self.c) self.run5.DEBUG=False self.run5.sim() self.grapher=1 self.graph=[0] self.graph[0]=Label(self.root,bg='white',text=('Durchschnitt: '+str(round(self.run5.getrel(),4))),font=('calibri',19)) self.graph[0].place(x=10,y=450) elif a=='Coins': self.run6=Coins(self.b) self.run6.sim() self.grapher=1 self.graph=[0,0] v=self.run6.geterg() vv=self.run6.getrel() self.graph[0]=Label(self.root,bg='white',text=('Statistik für www: '+str(v[0])+' '+str(vv[0])),font=('calibri',19)) self.graph[0].place(x=10,y=450) self.graph[1]=Label(self.root,bg='white',text=('Statistik für zwz: '+str(v[1])+' '+str(vv[1])),font=('calibri',19)) self.graph[1].place(x=10,y=500) def csvpressed(self): a=self.var1.get() if a=='Marriage': self.run0.exportcsv('Marriage_Simulation.csv') elif a=='Atom': self.run1.exportCSV('Atom_Simulation.csv') elif a=='Lotto': self.run4.exportCSV('Lotto_Simulation.csv') # def optioncanged(self,event): # a=self.var1.get() # if a=='Marriage': # self.csvbutton.destroy() # self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='green',borderwidth=5,command=self.csvpressed) # self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100) # elif a=='Atom': # self.csvbutton.destroy() # self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='green',borderwidth=5,command=self.csvpressed) # self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100) # elif a=='BubbleGum': # self.csvbutton.destroy() # self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='gray',borderwidth=5) # self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100) # elif a=='House_of_Cards': # self.csvbutton.destroy() # self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='gray',borderwidth=5) # self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100) # elif a=='Lotto': # self.csvbutton.destroy() # self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='green',borderwidth=5,command=self.csvpressed) # self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100) #elif a=='SecretSanta': # self.csvbutton.destroy() # self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='gray',borderwidth=5) # self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100) def MouseOneDown(self,event): if self.pressed==0: a=self.var1.get() if a=='Marriage': self.changer0=Text(self.root,bg='white',font=('Arial',30),borderwidth=1) self.changer0.place(y=100,x=int(self.x)-150,width=100,height=50) self.changer1=Label(self.root,text='Versuche:',bg='white',font=('Arial',30),borderwidth=1) self.changer1.place(y=100,x=int(self.x)-400,width=250,height=50) self.csvbutton.destroy() self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='green',borderwidth=5,command=self.csvpressed) self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100) elif a=='Atom': self.changer0=Text(self.root,bg='white',font=('Arial',30),borderwidth=1) self.changer0.place(y=100,x=int(self.x)-150,width=100,height=50) self.changer1=Label(self.root,text='Anzahl der Atome:',bg='white',font=('Arial',30),borderwidth=1) self.changer1.place(y=100,x=int(self.x)-600,width=450,height=50) self.changer2=Text(self.root,bg='white',font=('Arial',30),borderwidth=1) self.changer2.place(y=200,x=int(self.x)-150,width=100,height=50) self.changer3=Label(self.root,text='Zerfallswahrscheinlichkeit:',bg='white',font=('Arial',30),borderwidth=1) self.changer3.place(y=200,x=int(self.x)-650,width=500,height=50) self.csvbutton.destroy() self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='green',borderwidth=5,command=self.csvpressed) self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100) elif a=='BubbleGum': self.changer0=Text(self.root,bg='white',font=('Arial',30),borderwidth=1) self.changer0.place(y=100,x=int(self.x)-150,width=100,height=50) self.changer1=Label(self.root,text='Versuche:',bg='white',font=('Arial',30),borderwidth=1) self.changer1.place(y=100,x=int(self.x)-400,width=250,height=50) self.csvbutton.destroy() self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='gray',borderwidth=5) self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100) elif a=='House_of_Cards': self.changer0=Text(self.root,bg='white',font=('Arial',30),borderwidth=1) self.changer0.place(y=100,x=int(self.x)-150,width=100,height=50) self.changer1=Label(self.root,text='Versuche:',bg='white',font=('Arial',30),borderwidth=1) self.changer1.place(y=100,x=int(self.x)-400,width=250,height=50) self.changer2=Text(self.root,bg='white',font=('Arial',30),borderwidth=1) self.changer2.place(y=200,x=int(self.x)-150,width=100,height=50) self.changer3=Label(self.root,text='Kartenanzahl(32,55):',bg='white',font=('Arial',30),borderwidth=1) self.changer3.place(y=200,x=int(self.x)-620,width=450,height=50) self.csvbutton.destroy() self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='gray',borderwidth=5) self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100) elif a=='Lotto': self.changer0=Text(self.root,bg='white',font=('Arial',30),borderwidth=1) self.changer0.place(y=100,x=int(self.x)-150,width=100,height=50) self.changer1=Label(self.root,text='Versuche:',bg='white',font=('Arial',30),borderwidth=1) self.changer1.place(y=100,x=int(self.x)-400,width=250,height=50) self.changer2=Text(self.root,bg='white',font=('Arial',30),borderwidth=1) self.changer2.place(y=200,x=int(self.x)-150,width=100,height=50) self.changer3=Label(self.root,text='Version:',bg='white',font=('Arial',30),borderwidth=1) self.changer3.place(y=200,x=int(self.x)-400,width=250,height=50) self.csvbutton.destroy() self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='green',borderwidth=5,command=self.csvpressed) self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100) elif a=='SecretSanta': self.changer0=Text(self.root,bg='white',font=('Arial',30),borderwidth=1) self.changer0.place(y=100,x=int(self.x)-150,width=100,height=50) self.changer1=Label(self.root,text='Versuche:',bg='white',font=('Arial',30),borderwidth=1) self.changer1.place(y=100,x=int(self.x)-400,width=250,height=50) self.changer2=Text(self.root,bg='white',font=('Arial',30),borderwidth=1) self.changer2.place(y=200,x=int(self.x)-150,width=100,height=50) self.changer3=Label(self.root,text='Anzahl der Schüler:',bg='white',font=('Arial',30),borderwidth=1) self.changer3.place(y=200,x=int(self.x)-550,width=400,height=50) self.csvbutton.destroy() self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='gray',borderwidth=5) self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100) elif a=='Coins': self.changer0=Text(self.root,bg='white',font=('Arial',30),borderwidth=1) self.changer0.place(y=100,x=int(self.x)-150,width=100,height=50) self.changer1=Label(self.root,text='Versuche:',bg='white',font=('Arial',30),borderwidth=1) self.changer1.place(y=100,x=int(self.x)-400,width=250,height=50) self.csvbutton.destroy() self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='gray',borderwidth=5) self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100) self.pressed=1 else: try: self.c=self.changer2.get('1.0','end-1c') self.changer3.destroy() self.changer2.destroy() except (AttributeError,TclError): z=0 try: self.b=self.changer0.get('1.0','end-1c') self.changer1.destroy() self.changer0.destroy() except (AttributeError,TclError): z=0 if self.b=='': self.b=1 else: self.b=int(self.b) if self.c=='': self.c=1 else: self.c=int(float(self.c)) self.pressed=0
class ConfigurationWindow(Frame): """ Klasa GUI konfiguratora roweru w metodzie 'createBike' jest tworzony obiekt roweru z wykorzystaniem dekoratorów """ def __init__(self, parent, frames, forks, wheelsets, groups, components): """ inicjalizacja obiektu okna - nieistotne dla idei zdania """ super(ConfigurationWindow, self).__init__(parent) self._bike = None self.parent = parent self.frames = frames self.forks = forks self.wheelsets = wheelsets self.groups = groups self.components = components self.parent.title("Bicycle configurator") self._bike_price = StringVar(self.parent) self._bike_weight = StringVar(self.parent) self._bike_travel = StringVar(self.parent) self.price_label = Label(self.parent, textvariable=self._bike_price) self.weight_label = Label(self.parent, textvariable=self._bike_weight) self.travel_label = Label(self.parent, textvariable=self._bike_travel) self.createInterface() self.createBike() self.price_label.pack() self.weight_label.pack() self.travel_label.pack() self.pack(fill=BOTH, expand=1) def createInterface(self): """ Tworzenie interfejsu - nieistotne dla idei zadania """ self.frame_choice = StringVar(self.parent) self.frame_choice.set(tuple(self.frames.keys())[0]) self.frame_choice.trace("w", self.createBike) self.frame_options = OptionMenu(self.parent,self.frame_choice, *self.frames.keys()) Label(self.parent,text="Rama:").pack() self.frame_options.pack(fill=BOTH, expand=1) self.fork_choice = StringVar(self.parent) self.fork_choice.set(tuple(self.forks.keys())[0]) self.fork_choice.trace("w", self.createBike) self.fork_options = OptionMenu(self.parent,self.fork_choice, *self.forks.keys()) Label(self.parent,text="Widelec:").pack() self.fork_options.pack(fill=BOTH, expand=1) self.wheelset_choice = StringVar(self.parent) self.wheelset_choice.set(tuple(self.wheelsets.keys())[0]) self.wheelset_choice.trace("w", self.createBike) self.wheelset_options = OptionMenu(self.parent,self.wheelset_choice, *self.wheelsets.keys()) Label(self.parent,text="Koła:").pack() self.wheelset_options.pack(fill=BOTH, expand=1) self.group_choice = StringVar(self.parent) self.group_choice.set(tuple(self.groups.keys())[0]) self.group_choice.trace("w", self.createBike) self.group_options = OptionMenu(self.parent,self.group_choice, *self.groups.keys()) Label(self.parent,text="Grupa osprzętu:").pack() self.group_options.pack(fill=BOTH, expand=1) self.components_choice = StringVar(self.parent) self.components_choice.set(tuple(self.components.keys())[0]) self.components_choice.trace("w", self.createBike) self.components_options = OptionMenu(self.parent,self.components_choice, *self.components.keys()) Label(self.parent,text="Komponenty:").pack() self.components_options.pack(fill=BOTH, expand=1) def createBike(self, *args): """ Metoda tworząca obiekt roweru na zasadanie dekorowania obiektu klasy 'Frame' """ frame = self.frames[self.frame_choice.get()] fork = self.forks[self.fork_choice.get()] fork.decorated = frame wheelset = self.wheelsets[self.wheelset_choice.get()] wheelset.decorated = fork group = self.groups[self.group_choice.get()] group.decorated = wheelset components = self.components[self.components_choice.get()] components.decorated = group self._bike = components # przypisanie wartości odpowiednim elementom GUI self._bike_price.set("cena: " + str(self._bike.price) + "zł") self._bike_weight.set("waga: " + str(self._bike.weight) + " gr") self._bike_travel.set("skok: " + str(self._bike.travel) + " mm") # uaktualnienie okna self.price_label.update_idletasks() self.weight_label.update_idletasks() # zmiana tytułu okna self.parent.wm_title(self._bike.name)
def refreshWidget(self) : #print "refresh" self.card_win.pack_forget() import unicodedata #Card window self.card_win = PanedWindow(self.card_win.master, orient=VERTICAL) self.card_win.pack(side=TOP, expand=True, fill=BOTH, pady=2, padx=2) #Create the name zone name_zone=PanedWindow(self.card_win, orient=HORIZONTAL) name = StringVar() name.set(self.name) def modifName(*args) : try : assert('"' not in name.get()) name.get().encode('ascii') except Exception as e: print ("error on name") name.set(self.name) return old = self.name in Card.blocked_creature self.name=name.get() if old or self.name in Card.blocked_creature : self.refreshWidget() name.trace("w", modifName) name_wid=Entry(name_zone, width=30,textvariable=name) name_wid.pack() name_zone.add(name_wid) #Create the cost ad star stringvar #print int(floor(self.getCost())) self.cost=StringVar() self.stars=StringVar() cost_wid=Label(None, textvariable=self.cost, background='red',width=5, anchor=W) star_wid=Label(None, textvariable=self.stars, background='blue', anchor=E) self.cost.set(str(int(floor(self.getCost())))) self.stars.set("*"*self.getStars()) #Add them in name zone name_zone.add(cost_wid) name_zone.add(star_wid) #Create an Image Zone image_zone=Button(self.card_win, command=self.choosePhoto) if hasattr(self,"photofile") and self.photofile : print ("Image: ",self.photofile) try : pilImage=Image.open(self.photofile) img=PhotoImage(pilImage,master=image_zone) except : decomp=self.photofile.split('/') for i in range(1,6) : try : fname="/".join(decomp[-i:]) print ("try to open",fname) pilImage = Image.open(fname) img=PhotoImage(pilImage,master=image_zone) self.photofile=fname break except : self.photofile=None if self.photofile : w, h = img.width(), img.height() print('wh',w,h) if h>400 : print("reduction") img=PhotoImage(pilImage.resize((w//2,h//2), Image.ANTIALIAS),master=image_zone) image_zone=Button(self.card_win,image=img, command=self.choosePhoto) image_zone.image=img #image_zone.configure(image=image_zone.image,width=50,height=50,compound=RIGHT) #image_zone.pack() #print "IMAGE CHANGED" else : from os import path fname=self.name.replace(" ","_") if path.isfile("Cards/"+fname+".png") : image_zone.config(text='image can be taken from\n'+"Cards/"+fname+".png",background='white',anchor=CENTER) else : image_zone.config(text='clic to choose image',background='white',anchor=CENTER) #image_zone.pack() # POWER ZONE power_zone=PanedWindow(self.card_win, orient=VERTICAL) #fenetre=self.card_win.master def removePowerCreator(px) : def removePower(*args) : #print 'avant',list_pow self.bonus.remove(px) #print 'apres',list_pow #self.card_win.pack_forget() self.refreshWidget() return removePower for p in self.bonus : powline = PanedWindow(self.card_win, orient=HORIZONTAL) pow_wid=p.initWidget(powline) powline.add(pow_wid) removepow=Button(powline, text="X", command=removePowerCreator(p), anchor=E) removepow.pack() powline.add(removepow) power_zone.add(powline) def addPower(*args) : if addBonus.get()!= "add bonus": name=addBonus.get() else: name=add_cost_alteration.get() print ("added :",name) import CardPowers self.bonus+=[eval('CardPowers.'+name+'()')] self.bonus[-1].parent=self.bonus self.bonus[-1].card=self #self.card_win.pack_forget() self.refreshWidget() #Add bonus Option menu addBonus = StringVar(power_zone) addBonus.set("add bonus") # default value if not self.pv: addBonus_wid = Spell.getSpellMenu(power_zone, addBonus) else: addBonus_wid = getBonusMenu(power_zone, addBonus) addBonus.trace('w', addPower) if self.pv>0 or len(self.bonus)==0 or all([b.is_cost_alterator for b in self.bonus]): addBonus_wid.pack() #Add this to power zone power_zone.add(addBonus_wid) #Create save zone save_zone = PanedWindow(self.card_win, orient=HORIZONTAL) if self.monster_type != "all" and not(self.name in Card.blocked_creature) : save_wid = Button(save_zone, text="Save", command=self.postAndSave) elif self.monster_type != "all" : save_wid = Button(save_zone, text="creature in campaign", command=None) else: save_wid = Button(save_zone, text="nead type", command=None) save_wid.pack() #Create the open button save_zone.pack() if Card.monster_list.keys(): self.opening = StringVar(save_zone) self.opening.set("Open") choice = [na for na in Card.monster_list.keys() if na not in Card.blocked_creature] choice.sort() #print all_monsters.keys() open_wid = OptionMenu(save_zone, self.opening,*choice) self.opening.trace('w', self.Open) open_wid.pack() save_zone.add(open_wid) if Card.monster_list.keys(): self.delete = StringVar(save_zone) self.delete.set("Delete") choice = [na for na in Card.monster_list.keys() if na not in Card.blocked_creature] choice.sort() delete_wid = OptionMenu(save_zone, self.delete,*choice) self.delete.trace('w', self.clicDelete) delete_wid.pack() save_zone.add(delete_wid) #Create the type button self.category = StringVar(save_zone) self.category.set(self.monster_type) choice = [file2name(t,"_monsters.sav") for t in glob.glob("CardFiles/*_monsters.sav")] if "recup" in choice: choice.remove("recup") #print all_monsters.keys() category_wid = OptionMenu(save_zone, self.category,*choice) self.category.trace('w', self.setFile) category_wid.pack() #Add it to save zone save_zone.add(save_wid) save_zone.add(category_wid) #Create a new Strength zone for att and pv strength_zone=PanedWindow(self.card_win, orient=HORIZONTAL) att=StringVar() att.set(str(self.att)) pv=StringVar() ; pv.set(str(self.pv)) def modifiedAttPv(*args) : print ("modifiedAttPv") self.pv=int(pv.get()) if self.pv<1 and self.is_spell==False : if len(self.bonus)==0 : self.is_spell=True self.refreshWidget() else : self.pv=1 self.refreshWidget() if self.pv>0 and self.is_spell==True : if len(self.bonus)==0 : self.is_spell=False self.refreshWidget() else : self.pv=0 self.refreshWidget() self.att=int(att.get()) self.getCost() att_wid = Spinbox(strength_zone, from_=0, to=1000,textvariable=att,command=modifiedAttPv) att_wid.pack() strength_zone.add(att_wid) strength_zone.add(Label(strength_zone, text=' ', background='white', anchor=CENTER)) pv_wid = Spinbox(strength_zone, from_=0, to=1000,textvariable=pv,command=modifiedAttPv) pv_wid.pack() strength_zone.add(pv_wid) #Put it all in window self.card_win.add(name_zone) self.card_win.add(image_zone) self.card_win.add(power_zone) self.card_win.add(strength_zone) self.card_win.add(save_zone) self.card_win.pack()