예제 #1
0
    def populate_dbs(self):
        def select_db():
            self.selected_db_var = db_var
            selected_db = str(db_var.get())
            self.db_entry.delete(0, "end")
            self.db_entry.insert(0, selected_db)
            # we add the drop button, only if a radio-button is pressed
            self.drop_db_btn = Button(self.dbs_frm,
                                      text="Drop database",
                                      command=self.drop_db)
            self.drop_db_btn.grid(row=db_counter,
                                  column=2,
                                  pady=10,
                                  ipadx=5,
                                  ipady=2)

        db_var = StringVar()

        db_list = self.client.database_names(
        )  # we get the available database names of this connection

        db_counter = 0
        read_write.log_message("[INFO] (frames.DbFrame) : DBs found: " +
                               str(db_list))
        for name in db_list:
            r = Radiobutton(self.dbs_frm,
                            text=name,
                            variable=db_var,
                            value=name,
                            command=select_db)
            r.grid(row=db_counter, column=2, pady=2)
            db_counter += 1
예제 #2
0
    def populate_collections(self):
        def select_collection():
            self.selected_collection_var = collection_var
            selected_collection = str(collection_var.get())
            self.collection_entry.delete(0, "end")
            self.collection_entry.insert(0, selected_collection)
            # we add the drop button, only if a radio-button is pressed
            self.drop_collection_btn = Button(self.collections_frm,
                                              text="Drop collection",
                                              command=self.drop_collection)
            self.drop_collection_btn.grid(row=collection_counter,
                                          column=2,
                                          pady=10,
                                          ipadx=5,
                                          ipady=2)

        collection_var = StringVar()
        collection_list = [
        ]  # we get the available collection names of this connection but
        # only if a database name already exists
        if self.db_entry.get() is not "":
            collection_list = self.client[self.db_entry.get(
            )].collection_names(include_system_collections=False)

        collection_counter = 0  # this counter is responsible to place the radio-buttons into correct row
        for name in collection_list:
            r = Radiobutton(self.collections_frm,
                            text=name,
                            variable=collection_var,
                            value=name,
                            command=select_collection)
            r.grid(row=collection_counter, column=2, pady=2)
            collection_counter += 1
예제 #3
0
 def build_widgets(self):
     "Build the various widgets that will be used in the program."
     # Create processing frame widgets.
     self.processing_frame = LabelFrame(self, text='Processing Mode:')
     self.mode_var = StringVar(self, 'encode')
     self.decode_button = Radiobutton(self.processing_frame,
                                      text='Decode Cipher-Text',
                                      command=self.handle_radiobuttons,
                                      value='decode',
                                      variable=self.mode_var)
     self.encode_button = Radiobutton(self.processing_frame,
                                      text='Encode Plain-Text',
                                      command=self.handle_radiobuttons,
                                      value='encode',
                                      variable=self.mode_var)
     self.freeze_var = BooleanVar(self, False)
     self.freeze_button = Checkbutton(self.processing_frame,
                                      text='Freeze Key & Primer',
                                      command=self.handle_checkbutton,
                                      offvalue=False,
                                      onvalue=True,
                                      variable=self.freeze_var)
     # Create encoding frame widgets.
     self.encoding_frame = LabelFrame(self, text='Encoding Options:')
     self.chain_size_label = Label(self.encoding_frame, text='Chain Size:')
     self.chain_size_entry = Entry(self.encoding_frame)
     self.plain_text_label = Label(self.encoding_frame, text='Plain-Text:')
     self.plain_text_entry = Entry(self.encoding_frame)
     # Create input frame widgets.
     self.input_frame = LabelFrame(self, text='Input Area:')
     self.input_text = ScrolledText(self.input_frame, **self.TEXT)
     # Create output frame widgets.
     self.output_frame = LabelFrame(self, text='Output Area:')
     self.output_text = ScrolledText(self.output_frame, **self.TEXT)
예제 #4
0
    def initUI(self):

        self.master.title("Text Encryption")
        self.pack(fill=BOTH, expand=True)

        self.frame1 = Frame(self)
        self.frame1.pack()

        self.lbl3 = Label(self.frame1, text="original text", width=25)
        self.lbl3.pack(side=LEFT, anchor=N, padx=5, pady=5)

        self.txt = Text(self.frame1, width=100, height=10)
        self.txt.pack(fill=BOTH, pady=25, padx=25, expand=True)

        self.frame2 = Frame(self)
        self.frame2.pack()
        self.btn1 = Button(self.frame2, text="process", command=self.pushButton)
        self.btn1.pack()
        self.type = StringVar(self.frame2, "encrypt")
        self.radio1 = Radiobutton(self.frame2, text='encrypt', value='encrypt', variable=self.type)
        self.radio2 = Radiobutton(self.frame2, text='decrypt', value='decrypt', variable=self.type)
        self.radio1.pack()
        self.radio2.pack()


        self.frame5 = Frame(self)
        self.frame5.pack()
        self.lbl4 = Label(self.frame5, text="processed text", width=25)
        self.lbl4.pack(side=LEFT, anchor=N, padx=5, pady=5)

        self.txt1 = Text(self.frame5, width=100, height=10)
        self.txt1.pack( pady=25, padx=25 )

        self.frame6 = Frame(self)
        self.frame6.pack()
        self.lbl5 = Label(self.frame6, text="settings", width=10)
        self.lbl5.pack(side=LEFT, anchor=N, padx=5, pady=5)

        #setting up the combo
        allProperties = self.db.getAllProperies()
        comboContent = []
        for x in allProperties:
            comboContent.append(x[1])
        self.combo = Combobox(self.frame6,text= 'preporty', values=comboContent)
        self.combo.pack()

        self.combo.bind('<<ComboboxSelected>>', self.comboModified)

        self.frame7 = Frame(self)
        self.frame7.pack()

        self.lbl6 = Label(self.frame7, text="value", width=10)
        self.lbl6.pack(side=LEFT, anchor=N, padx=5, pady=5)


        self.entry = Entry(self.frame7)
        self.entry.pack()

        self.btn2 = Button(self.frame7, text='Save')
        self.btn2.pack()
예제 #5
0
    def creat_res(self):
        self.v = IntVar()  # 书籍查询
        self.v.set(True)
        self.temp = StringVar()  # 书名/作者 录入
        self.temp2 = StringVar()  # 章节名录入
        self.sys_time = StringVar()  # 系统时间

        self.E_startstation = Entry(self.win, textvariable=self.temp)
        self.E_endstation = Entry(self.win, textvariable=self.temp2)

        self.La_startstation = Label(self.win, text="根据书名/作者搜索:")
        self.La_endstation = Label(self.win, text="根据章节名搜索:")
        self.La_directory = Label(self.win, text="目录")
        self.La_text = Label(self.win, text="正文")
        self.La_sys_time = Label(self.win, textvariable=self.sys_time, fg='blue', font=("黑体", 20))  # 设置字体大小颜色

        self.B_search = Button(self.win, text="搜索")
        self.B_buy_tick = Button(self.win, text="阅读")
        self.B_pre_chapter = Button(self.win, text="上一章")
        self.B_next_chapter = Button(self.win, text="下一章")

        self.R_site = Radiobutton(self.win, text="书名查询", variable=self.v, value=True)
        self.R_price = Radiobutton(self.win, text="章节查询", variable=self.v, value=False)

        self.init_data_Text = Text(self.win)  # 原始数据录入框
        self.S_move = Scrollbar(self.win)  # 目录滚动条
        self.S_text_move = Scrollbar(self.win)  # 创建文本框滚动条
예제 #6
0
파일: gui.py 프로젝트: Potriashka/tdgeGUI
def new_object():
    icn = Label(tab2, text="Name of the object", font=("Arial Bold", 10))
    icn.place(x=8, y=20)

    size = Label(tab2, text="Size", font=("Arial Bold", 10))
    size.place(x=43, y=70)

    aw = Label(tab2, text="a", font=("Arial Bold", 10))
    aw.place(x=29, y=110)

    global a
    a = Entry(tab2, width=3)
    a.place(x=25, y=95)

    bw = Label(tab2, text="b", font=("Arial Bold", 10))
    bw.place(x=59, y=110)

    global b
    b = Entry(tab2, width=3)
    b.place(x=55, y=95)

    cw = Label(tab2, text="c", font=("Arial Bold", 10))
    cw.place(x=89, y=110)

    global c
    c = Entry(tab2, width=3)
    c.place(x=85, y=95)

    nameOO = Entry(tab2, width=15)
    nameOO.place(x=18, y=45)

    typeCUBE = Radiobutton(tab1, text='Color bg', value=1, command=typechuz)
    typeCUBE.place(x=20, y=200)
 def build_widgets(self):
     "Build the various widgets that will be used in the program."
     # Create processing frame widgets.
     self.processing_frame = LabelFrame(self, text='Processing Mode:')
     self.mode_var = StringVar(self, 'encode')
     self.decode_button = Radiobutton(self.processing_frame,
                                      text='Decode Cipher-Text',
                                      command=self.handle_radiobuttons,
                                      value='decode',
                                      variable=self.mode_var)
     self.encode_button = Radiobutton(self.processing_frame,
                                      text='Encode Plain-Text',
                                      command=self.handle_radiobuttons,
                                      value='encode',
                                      variable=self.mode_var)
     self.freeze_var = BooleanVar(self, False)
     self.freeze_button = Checkbutton(self.processing_frame,
                                      text='Freeze Key & Primer',
                                      command=self.handle_checkbutton,
                                      offvalue=False,
                                      onvalue=True,
                                      variable=self.freeze_var)
     # Create encoding frame widgets.
     self.encoding_frame = LabelFrame(self, text='Encoding Options:')
     self.chain_size_label = Label(self.encoding_frame, text='Chain Size:')
     self.chain_size_entry = Entry(self.encoding_frame)
     self.plain_text_label = Label(self.encoding_frame, text='Plain-Text:')
     self.plain_text_entry = Entry(self.encoding_frame)
     # Create input frame widgets.
     self.input_frame = LabelFrame(self, text='Input Area:')
     self.input_text = ScrolledText(self.input_frame, **self.TEXT)
     # Create output frame widgets.
     self.output_frame = LabelFrame(self, text='Output Area:')
     self.output_text = ScrolledText(self.output_frame, **self.TEXT)
예제 #8
0
파일: main.py 프로젝트: toky0s/XImage
    def setupUI(self):
        frame_group_option = Frame(self)
        frame_group_option.grid(row=0, column=0)

        self.var_frame_group_option = IntVar()
        self.var_frame_group_option.set(1)  # set UI for app

        icon_unsplash = PhotoImage(file='icon/photo-camera.png')
        radiobutton_unsplash_ui = Radiobutton(
            frame_group_option,
            text='Unsplash',
            image=icon_unsplash,
            variable=self.var_frame_group_option,
            value=1,
            command=self.set_ui,
            compound='left')
        radiobutton_unsplash_ui.image = icon_unsplash

        icon_graphicriver = ImageTk.PhotoImage(file='icon/graphicriver.png')
        radiobutton_graphicriver_ui = Radiobutton(frame_group_option)
        radiobutton_graphicriver_ui['text'] = 'GraphicRiver'
        radiobutton_graphicriver_ui['image'] = icon_graphicriver
        radiobutton_graphicriver_ui.image = icon_graphicriver
        radiobutton_graphicriver_ui['compound'] = 'left'
        radiobutton_graphicriver_ui['variable'] = self.var_frame_group_option
        radiobutton_graphicriver_ui['value'] = 2
        radiobutton_graphicriver_ui['command'] = self.set_ui

        radiobutton_unsplash_ui.pack(side='left')
        radiobutton_graphicriver_ui.pack(side='left')

        self.unsplash_ui = UnsplashUI(self)
        self.unsplash_ui.grid(row=1, column=0, sticky='w')
예제 #9
0
 def creat_radiores(self):
     self.movie=StringVar()#电影
     self.S_croll2=Scrollbar()#分集
     self.La_pic=Label(self.win,bg="#E6E6FA")
     self.La_movie_message=Listbox(self.win,bg="#7EC0EE")
     self.R_movie=Radiobutton(self.win,text="电影",variable=self.movie,value="m")
     self.tv=Radiobutton(self.win,text="电视剧",variable=self.movie,value="t")
     self.zhongyi=Radiobutton(self.win,text="综艺",variable=self.movie,value="z")
     self.dongman=Radiobutton(self.win,text="动漫",variable=self.movie,value="d")
     self.jilupian=Radiobutton(self.win,text="排行榜",variable=self.movie,value="j")
     self.movie.set('m')
     self.B_view=Button(self.win,text="查看")
     self.B_info=Button(self.win,text="使用说明")
     self.B_clearbox=Button(self.win,text="清空列表")
     self.B_add=Button(self.win,text="打开浏览器观看")
     self.R_movie.place(x=290,y=280,width=80,height=30)
     self.B_view.place(x=290,y=430,width=70,height=30)
     self.B_add.place(x=370,y=255,width=100,height=30)
     self.B_clearbox.place(x=500,y=255,width=70,height=30)
     self.tv.place(x=290,y=310,width=80,height=30)
     self.zhongyi.place(x=290,y=340,width=80,height=30)
     self.dongman.place(x=290,y=370,width=80,height=30)
     self.jilupian.place(x=290,y=400,width=80,height=30)
     self.La_movie_message.place(x=370,y=290,width=200,height=220)
     self.La_pic.place(x=370,y=10,width=200,height=240)
     self.B_info.place(x=290,y=470,width=70,height=30)
     self.S_croll2.place(x=568,y=290,width=20,height=220)
    def __init__(self, parent, *args, **kwargs):
        Frame.__init__(self, parent)
        self.tree = Treeview(self)
        self.tree['selectmode'] = "browse"
        self.tree['columns'] = ('ID', 'Name', 'Gram', 'Include')
        self.tree['height'] = 30
        self.tree['show'] = "headings"
        self.tree.heading('ID', text="ID")
        self.tree.heading('Name', text="Name")
        self.tree.heading('Gram', text="Quantity [mmol]")
        self.tree.heading('Include', text="Include")
        self.tree.column('ID', minwidth=0, width=20)
        self.tree.column('Name', minwidth=100, width=100)
        self.tree.column('Gram', minwidth=0, width=90)
        self.tree.column('Include', minwidth=50, width=50)
        self.tree.bind('<ButtonRelease-1>', self.select_item)
        self.tree.grid(row=0, column=0, columnspan=4)
        self.run_object = kwargs.pop('run_object', None)

        self.medium = None
        self.medium_volume = None
        self.uptake_quantities = {}
        self.species_names = []

        self.pie_figure, self.piechart = plt.subplots()
        self.pie_figure.figsize = (4, 4)
        self.piechart.pie([0, 0])
        self.canvas = FigureCanvasTkAgg(self.pie_figure, master=self)
        self.canvas.draw()
        self.canvas.get_tk_widget().grid(row=0, column=4, padx=10)

        Label(self, text="Quantity:").grid(row=1, column=0)
        self.edit_entry = FloatEntry(self, initial_value='')
        self.edit_entry.grid(row=1, column=1, sticky='w')
        Button(self, text="Save Changes",
               command=self.save_changes).grid(row=1, column=2, rowspan=2)

        self.rad_var = IntVar()
        self.rad_button_exclude = Radiobutton(self,
                                              text="No",
                                              variable=self.rad_var,
                                              value=0)
        self.rad_button_include = Radiobutton(self,
                                              text="Yes",
                                              variable=self.rad_var,
                                              value=1)
        self.rad_button_include.grid(row=2, column=1, sticky='w')
        self.rad_button_exclude.grid(row=2, column=1, sticky='e')
        Label(self, text="Include:").grid(row=2, column=0)
        Label(self, text="Medium Name:").grid(row=3, column=0)
        self.name_entry = StringEntry(self, initial_value="refined_medium")
        self.name_entry.grid(row=3, column=1, sticky='w')

        Button(self, text="Test Medium", command=parent.plot).grid(row=4,
                                                                   column=1)
        Button(self,
               text="Save Medium",
               command=lambda: self.save_medium(parent.save)).grid(row=3,
                                                                   column=2)
예제 #11
0
    def initialise_starting_window(self):
        self.starting_window = Tk()
        # self.starting_window.configure(bg = "#63C77C")
        text = Label(self.starting_window,
                     text="знайдіть вірш за назвою, або введіть власний")
        text.pack()

        self.input = Entry(self.starting_window)
        self.input.pack()

        self.starting_window.title("Lacalut")
        self.starting_window.geometry('350x600')

        self.lbl = Label(self.starting_window, text="")
        self.lbl.pack()

        self.enter_custom_btn = Button(
            self.starting_window,
            text="ввести власний вірш",
            bg="#315EBB",
            command=self.initialise_custom_verse_window)
        self.enter_custom_btn.pack()

        self.submit_verse_btn = Button(self.starting_window,
                                       text="підтвердити вірш",
                                       bg="#315EBB",
                                       command=self.submit_verse)
        self.submit_verse_btn.pack()

        self.user_verse_preview = Label(
            self.starting_window,
            text="*тут буде відображатися прев'ю вашого вірша*",
            fg="#616264",
            height=25)
        self.user_verse_preview.pack()

        self.selected = IntVar()

        self.rad1 = Radiobutton(self.starting_window,
                                text='режим перевірки в прямому часі',
                                value=1,
                                variable=self.selected)
        self.rad1.pack()
        self.rad2 = Radiobutton(self.starting_window,
                                text='режим пост аналізу',
                                value=2,
                                variable=self.selected)
        self.rad2.pack()

        self.move_to_analisys_btn = Button(self.starting_window,
                                           text="proceed to studying",
                                           command=self.proceed_with_settings,
                                           bg="#315EBB")
        self.move_to_analisys_btn.pack()
        # self.btn1 = Button(self.starting_window, text="print verse", bg = "#315EBB", command = self.print_custom_verse)
        # self.btn1.pack()

        self.starting_window.mainloop()
예제 #12
0
    def setupUI(self):

        self.variable.set(self.initialize)  # initialize
        for text, value in self.dict_option.items():
            radiobt_quality = Radiobutton(self,
                                          text=text,
                                          variable=self.variable,
                                          value=value)
            radiobt_quality.pack(side=self.side, anchor='w')
예제 #13
0
 def creat_res(self):
     self.temp = StringVar()  # url地址
     self.temp2 = StringVar()
     self.t1 = StringVar()  # 通道
     self.t3 = StringVar()  # 爱奇艺,优酷,PPTV
     self.La_title = Label(self.win, text="地址:")
     self.La_way = Label(self.win, text="选择视频通道:")
     self.R_way1 = Radiobutton(self.win,
                               text="通道A",
                               variable=self.t1,
                               value=True)
     self.R_way2 = Radiobutton(self.win,
                               text="通道B",
                               variable=self.t1,
                               value=False)
     self.R_aiqiyi = Radiobutton(self.win,
                                 text="爱奇艺",
                                 variable=self.t3,
                                 value="a")
     self.R_youku = Radiobutton(self.win,
                                text="优酷",
                                variable=self.t3,
                                value="y")
     self.R_pptv = Radiobutton(self.win,
                               text="PPTV",
                               variable=self.t3,
                               value="p")
     self.B_play = Button(self.win, text="播放▶")
     self.B_uppage = Button(self.win, text="上页")
     self.B_nextpage = Button(self.win, text="下页")
     self.B_search = Button(self.win, text="♣搜索全站♠")
     self.La_mesasge = Label(self.win, text="☜  ⇠☸⇢  ☞", bg="pink")
     self.La_page = Label(self.win, bg="#BFEFFF")
     self.S_croll = Scrollbar(self.win)
     self.L_box = Listbox(self.win, bg="#BFEFFF", selectmode=SINGLE)
     self.E_address = Entry(self.win, textvariable=self.temp)
     self.La_title.place(x=10, y=50, width=50, height=30)
     self.E_address.place(x=70, y=50, width=200, height=30)
     self.B_play.place(x=300, y=50, width=50, height=30)
     self.R_way1.place(x=160, y=10, width=70, height=30)
     self.R_way2.place(x=240, y=10, width=70, height=30)
     self.La_way.place(x=10, y=10, width=100, height=30)
     self.R_aiqiyi.place(x=20, y=100, width=70, height=30)
     self.R_youku.place(x=90, y=100, width=70, height=30)
     self.R_pptv.place(x=160, y=100, width=70, height=30)
     self.B_search.place(x=252, y=140, width=100, height=30)
     self.La_mesasge.place(x=80, y=125, width=90, height=20)
     self.L_box.place(x=10, y=180, width=252, height=230)
     self.S_croll.place(x=260, y=180, width=20, height=230)
     self.B_uppage.place(x=10, y=140, width=50, height=30)
     self.B_nextpage.place(x=180, y=140, width=50, height=30)
     self.La_page.place(x=80, y=150, width=90, height=28)
예제 #14
0
파일: searchbase.py 프로젝트: 1st1/cpython
    def create_other_buttons(self):
        '''Return (frame, others) for testing.

        Others is a list of value, label pairs.
        A gridded frame from make_frame is filled with radio buttons.
        '''
        frame = self.make_frame("Direction")[0]
        var = self.engine.backvar
        others = [(1, 'Up'), (0, 'Down')]
        for val, label in others:
            btn = Radiobutton(frame, variable=var, value=val, text=label)
            btn.pack(side="left", fill="both")
        return frame, others
예제 #15
0
    def create_other_buttons(self):
        '''Return (frame, others) for testing.

        Others is a list of value, label pairs.
        A gridded frame from make_frame is filled with radio buttons.
        '''
        frame = self.make_frame("Direction")[0]
        var = self.engine.backvar
        others = [(1, 'Up'), (0, 'Down')]
        for val, label in others:
            btn = Radiobutton(frame, variable=var, value=val, text=label)
            btn.pack(side="left", fill="both")
        return frame, others
예제 #16
0
    def _setup_widgets(self):
        l = Label(self.fr,
                  text="Dont't forget click and hover, \n \
or see more by using the radio buttons")
        l.grid(column=0, row=0, columnspan=3, padx=5, pady=2, sticky='n')
        themes = sorted(list(self.style.theme_names()))
        # Create rasio buttons which will display themes
        self.theme_val = StringVar()
        for ix, val in enumerate(themes):
            themes_rb = Radiobutton(self.fr,
                                    value=val,
                                    text=val,
                                    variable=self.theme_val,
                                    command=self._change_theme)
            themes_rb.grid(column=0, row=ix + 1, padx=5, pady=2, sticky='nw')

        states = [
            'active', 'alternate', 'background', 'disabled', 'focus',
            'invalid', 'pressed', 'readonly', 'selected'
        ]
        # Create rasio buttons which will display widget states
        self.state_val = StringVar()
        for iy, state in enumerate(states):
            st_rb = Radiobutton(self.fr,
                                value=state,
                                text=state,
                                variable=self.state_val,
                                command=self._change_state)
            st_rb.grid(column=1, row=iy + 1, padx=5, pady=5, sticky='nw')

        # selected widget, if using scrollbar place in own frame
        self.but = Button(self.fr, text='Button State')
        self.but.grid(column=3, row=ix + 2, padx=5, pady=5)
예제 #17
0
 def __init__(self, parent, values, callback, **kwargs):
     super().__init__(parent, **kwargs)
     self.callback = callback
     self.selected_option = StringVar(self.frame)
     self.selected_option.set(values[0])
     self.options = []
     for value in values:
         option = Radiobutton(self.frame,
                              text=value,
                              value=value,
                              variable=self.selected_option,
                              command=self._option_changed)
         option.grid(padx=5, pady=5, sticky=W)
         self.options.append(option)
예제 #18
0
 def creat_res(self):
     self.temp = StringVar()
     self.num = StringVar()  # 截图数量
     self.water = StringVar()  # 是否水印
     self.pics = StringVar()  # 是否截图
     self.L_enter = Label(self.w, text='请输入抖音分享链接', fg='#32CD32')
     self.L_res = Label(self.w, text='信息', bg='#F0FFF0', fg="#B452CD")
     self.L_message = Label(self.w, text='', bg='#71C671')
     self.E_enter = Entry(self.w, textvariable=self.temp)
     self.B_go = Button(self.w, text='GO')
     self.L_box = Listbox(self.w)
     self.S_bal = Scrollbar(self.w, orient=VERTICAL, bg='red')
     self.S_x_bal = Scrollbar(self.w, orient=HORIZONTAL, bg='red')
     self.R_water1 = Radiobutton(self.w,
                                 text='有水印',
                                 variable=self.water,
                                 value='1')
     self.R_water2 = Radiobutton(self.w,
                                 text='无水印',
                                 variable=self.water,
                                 value='2')
     self.R_savepic1 = Radiobutton(self.w,
                                   text='截图张数',
                                   variable=self.pics,
                                   value='1')
     self.R_savepic2 = Radiobutton(self.w,
                                   text='不截图',
                                   variable=self.pics,
                                   value='2')
     self.E_num_pics = Entry(self.w, textvariable=self.num)
     self.res_place()
     self.res_config()
예제 #19
0
 def type_search(self):
     label = Label(self,
                   text='Расширенный поиск ',
                   font=('Arial Bold', 25),
                   bg="#b2bfbb")
     label.place(x=230, y=10)
     self.geometry('900x600')
     self.title('Поиск по критериям')
     label_choice = Label(self,
                          text='Выберите тип поиска: ',
                          font=('Arial', 17),
                          bg="#b2bfbb")
     label_choice.place(x=20, y=65)
     global var
     var = IntVar()
     rad1 = Radiobutton(self,
                        text='Поиск по одному критерию',
                        value=1,
                        variable=var,
                        command=self.selected_search)
     rad2 = Radiobutton(self,
                        text='Поиск по нескольким критериям',
                        value=2,
                        variable=var,
                        command=self.selected_search)
     rad1.place(x=20, y=115)
     rad2.place(x=20, y=140)
예제 #20
0
 def creat_res(self):
     self.v = IntVar()  # 车票查询
     self.v.set(True)
     self.temp = StringVar()  # 开始站
     self.temp2 = StringVar()  # 目的站
     self.start_mon = StringVar()  # 出发月
     self.start_day = StringVar()  # 出发日
     self.start_year = StringVar()  # 出啊年
     self.La_start_end = Label(self.win, text="请输入出发地和目的地", fg="blue")
     self.E_startstation = Entry(self.win, textvariable=self.temp)
     self.E_endstation = Entry(self.win, textvariable=self.temp2)
     self.La_startstation = Label(self.win, text="出发站:")
     self.La_endstation = Label(self.win, text="目的站:")
     self.La_time = Label(self.win, text="请选择出发时间-年-月-日", fg="blue")
     self.B_search = Button(self.win, text="搜索")
     self.R_site = Radiobutton(self.win,
                               text="车票查询",
                               variable=self.v,
                               value=True)
     self.R_price = Radiobutton(self.win,
                                text="票价查询",
                                variable=self.v,
                                value=False)
     self.B_buy_tick = Button(self.win, text="购票")
     self.C_year = Combobox(self.win, textvariable=self.start_year)
     self.La_s = Label(self.win, text="--")
     self.C_mon = Combobox(self.win, textvariable=self.start_mon)
     self.La_s1 = Label(self.win, text="--")
     self.C_day = Combobox(self.win, textvariable=self.start_day)
     # 滚动条
     self.S_move = Scrollbar(self.win)
     self.La_start_end.place(x=10, y=10, width=150, height=30)
     self.E_startstation.place(x=70, y=50, width=145, height=30)
     self.E_startstation.insert(10, "杭州东")
     self.E_endstation.place(x=70, y=100, width=145, height=30)
     self.E_endstation.insert(10, "南京南")
     self.La_startstation.place(x=10, y=50, width=50, height=30)
     self.La_endstation.place(x=10, y=100, width=50, height=30)
     self.La_time.place(x=0, y=140, width=190, height=30)
     self.C_year.place(x=10, y=180, width=70, height=30)
     self.La_s.place(x=80, y=180, width=20, height=30)
     self.C_mon.place(x=100, y=180, width=50, height=30)
     self.La_s1.place(x=150, y=180, width=20, height=30)
     self.C_day.place(x=170, y=180, width=50, height=30)
     self.B_search.place(x=10, y=220, width=80, height=40)
     self.S_move.place(x=1100, y=40, width=30, height=550)
     self.B_buy_tick.place(x=10, y=310, width=80, height=40)
     self.R_site.place(x=10, y=270, width=90, height=30)
     self.R_price.place(x=100, y=270, width=90, height=30)
예제 #21
0
 def __init__(self, active_mode: str = 'CBC', *args, **kwargs):
     """
     :param str active_mode: default selected mode (default is CBC). Possible modes: ECB, CBC, CFB, OFB
     """
     super(ModeChooser, self).__init__(*args, **kwargs)
     self._active_mode = StringVar()
     self._active_mode.set(1)
     label = tk.Label(self, text='Select mode:')
     label.pack()
     for text, mode in self.MODES:
         rb = Radiobutton(self,
                          text=text,
                          variable=self._active_mode,
                          value=mode)
         rb.pack(side=tk.LEFT)
예제 #22
0
def visual(r):
    """Отображение всех вопросов с 2 по 7 (10)"""
    global ans
    ques = Label(window, text=phrases[r][0], font=("Helvetica", int(yax*0.0345)+2, 'italic'))
    ques.place(relx=0.5, rely=0.2, anchor=CENTER)

    ans = phrases[r][1:]

    if r not in (1, 2):
        selected = IntVar()
        buts = []
        for i in range(len(ans)):
            buts.append(Radiobutton(window, text=ans[i], value=i+1, variable=selected))

        for k in range(len(buts)):
            buts[k].place(relx=0.5, rely=0.2, y=int(yax*0.2)+(int(yax*0.07)*k+1), width=int(xax*0.55), anchor=CENTER)

        return selected

    else:
        if r == 1:
            Label(window, text='Введите калибр системы (мм):', font=("Helvetica", int(yax * 0.0205))).place(relx=0.5, rely=0.4, anchor=CENTER)
        else:
            Label(window, text='Введите массу боеприпаса системы (кг):', font=("Helvetica", int(yax * 0.0205))).place(relx=0.5, rely=0.4, anchor=CENTER)
        txt = Entry(window, width=int(xax*0.05), font=("Arial", int(yax * 0.018)))
        txt.place(relx=0.5, rely=0.2, y=int(yax*0.2)+(int(yax*0.07)), width=int(xax*0.15), height=int(xax*0.03), anchor=CENTER)

        return txt
    def _create_file_format_btn(self, btn_text, var_value, parent, column):
        ''' Creates and grids Radiobutton used for choosing solution file
            format.

            Args:
                btn_text (str): text displayed next to the Radiobutton.
                var_value (int): value of the IntVar associated with this
                    Radiobutton.
                parent (Tk object): parent of this Radiobutton.
                column (int): column index where this Radiobutton
                    should be gridded.
        '''
        sol_format_btn = Radiobutton(parent, text=btn_text,
                                     variable=self.solution_format_var,
                                     value=var_value)
        sol_format_btn.grid(row=2, column=column, sticky=W+N, padx=2)
예제 #24
0
파일: example.py 프로젝트: KlopotovGleb/376
    def __init__(self, parent: Tk or Toplevel, param_ids: List[int]):
        Frame.__init__(self, parent)
        self.parent = parent
        self.param_ids = param_ids
        self.paragraph_params = [
            param_id for param_id in param_ids if not PARAMS[param_id].is_run
        ]
        self.run_params = [
            param_id for param_id in param_ids if PARAMS[param_id].is_run
        ]

        self.pack(fill=BOTH, expand=1)
        self.centerWindow()

        self.parent.title('Введите параметры для анализа')
        self.addButton = Button(self,
                                text="Начать анализ",
                                command=self.new_test)
        self.addButton.place(x=247, y=360)
        self.user_input = {
            param_id: StringVar()
            for param_id in self.param_ids
        }

        indent = 0
        for param_id in self.param_ids:
            param = PARAMS[param_id]
            lbl = Label(self, text=param.name)
            lbl.place(x=10, y=10 + indent)
            scnd_row_x = 270
            if param.is_boolean:
                radio_btn = Radiobutton(self,
                                        variable=self.user_input[param_id],
                                        value="Нет")
                radio_btn.place(x=scnd_row_x, y=10 + indent)

                lbl_yes = Label(self, text="Нет")
                lbl_yes.place(x=scnd_row_x + 20, y=10 + indent)

                radio_btn = Radiobutton(self,
                                        variable=self.user_input[param_id],
                                        value="Да")
                radio_btn.place(x=scnd_row_x + 50, y=10 + indent)

                lbl_yes = Label(self, text="Да")

                lbl_yes.place(x=scnd_row_x + 70, y=10 + indent)
                self.user_input[param_id].set("Нет")

            else:
                text_field = Combobox(self,
                                      textvariable=self.user_input[param_id])
                text_field['values'] = param.default_vals
                text_field.current(param.start_val)
                text_field.place(x=scnd_row_x, y=10 + indent)

            indent += 23
예제 #25
0
    def _create_file_format_btn(self, btn_text, var_value, parent, column):
        ''' Creates and grids Radiobutton used for choosing solution file
            format.

            Args:
                btn_text (str): text displayed next to the Radiobutton.
                var_value (int): value of the IntVar associated with this
                    Radiobutton.
                parent (Tk object): parent of this Radiobutton.
                column (int): column index where this Radiobutton
                    should be gridded.
        '''
        sol_format_btn = Radiobutton(parent,
                                     text=btn_text,
                                     variable=self.solution_format_var,
                                     value=var_value)
        sol_format_btn.grid(row=2, column=column, sticky=W + N, padx=2)
예제 #26
0
 def creat_res(self):
     self.music_temp = StringVar(value="(.)(.)")
     self.mp3_lis = []  #备用
     self.temp = StringVar()  #url输入框
     self.temp2 = IntVar()  #单选框 播放或者下载
     self.temp3 = StringVar()  #path 输入框
     self.T_message = Listbox(self.win, background="#EEE9E9")
     self.B_search = Button(self.win, text="搜索")
     self.B_path = Button(self.win, text="选择目录")
     self.E_song = Entry(self.win, textvariable=self.temp)
     self.E_path = Entry(self.win, textvariable=self.temp3)
     self.Play_button = Button(self.win, text="播放")
     self.Pause_button = Button(self.win, textvariable=self.music_temp)
     self.Temp_button = Button(self.win, text="单曲下载")
     self.Stop_button = Button(self.win, text="停止")
     self.Info = Button(self.win, text="说明")
     self.More_down = Button(self.win, text="歌单批量下载")
     self.B_search_loacl = Button(self.win, text="扫描本地歌曲")
     self.S_bal = Scrollbar(self.win)
     self.R_1 = Radiobutton(self.win,
                            variable=self.temp2,
                            text="下载",
                            value=True)
     self.R_2 = Radiobutton(self.win,
                            variable=self.temp2,
                            text="播放",
                            value=False)
     self.L_mp3_message = Label(self.win,
                                background="#EEE9E9",
                                fg="#9370DB")
     self.B_search.place(x=340, y=5, width=50, height=30)
     self.E_song.place(x=10, y=10, width=300, height=35)
     self.T_message.place(x=10, y=165, width=280, height=200)
     self.Play_button.place(x=340, y=160, width=50, height=40)
     self.Pause_button.place(x=340, y=209, width=50, height=40)
     self.Temp_button.place(x=130, y=125, width=100, height=30)
     self.S_bal.place(x=286, y=165, width=20, height=200)
     self.E_path.place(x=10, y=70, width=200, height=40)
     self.B_path.place(x=230, y=75, width=60, height=38)
     self.L_mp3_message.place(x=241, y=125, width=152, height=30)
     self.Info.place(x=340, y=315, width=50, height=40)
     self.More_down.place(x=10, y=125, width=100, height=30)
     self.B_search_loacl.place(x=300, y=75, width=100, height=38)
     self.R_1.place(x=265, y=50, width=60, height=25)
     self.R_2.place(x=340, y=50, width=60, height=25)
     self.Stop_button.place(x=340, y=260, width=50, height=40)
예제 #27
0
    def initUI(self):
        self.parent.title("T431")
        self.pack(fill=BOTH, expand=True)
        global value
        value = 0
        global v
        v = IntVar()
        v.set(1)
        
        global exp
        exp = StringVar()
        global res
        res = StringVar()

        frame1 = Frame(self,style='My.TFrame')
        frame1.pack(fill=X)
		
        
        rb1 = Radiobutton(frame1, text = "4*3^n-1", variable = v, value = 1,style='My.TRadiobutton')
        rb1.pack( anchor = W )
		
        rb2 = Radiobutton(frame1, text = "4*3^n+1", variable = v, value = 2,style='My.TRadiobutton')
        rb2.pack( anchor = W )
		
        
       
		
        frame2 = Frame(self,style='My.TFrame')
        frame2.pack(fill=X)

        lbl2 = Label(frame2, text="Enter the exponent :", width=18,background='orange')
        lbl2.pack(side=LEFT, padx=5, pady=5)

        entry2 = Entry(frame2,textvariable=exp,style='My.TEntry')
        entry2.pack(fill=X, padx=5, expand=True)

        
        frame3 = Frame(self,style='My.TFrame')
        frame3.pack(fill=X)

        result = Label(frame3, textvariable=res, width=42,background='orange')
        result.pack(side=LEFT, padx=60, pady=5)

		
        frame4 = Frame(self,style='My.TFrame')
        frame4.pack(fill=X)

        btntest = Button(frame4, text="Test", width=10, command=self.test,style='My.TButton')
        btntest.pack(side=LEFT, anchor=N, padx=5, pady=5)
		
        btnclear = Button(frame4, text="Clear", width=10, command=self.clear,style='My.TButton')
        btnclear.pack(side=LEFT, anchor=N, padx=5, pady=5)
		
        btnclose = Button(frame4, text="Close", width=10, command=self.quit,style='My.TButton')
        btnclose.pack(side=LEFT, anchor=N, padx=5, pady=5)
예제 #28
0
def tkinter_create_window():
    global days_input
    global hashtag_input
    global like_input
    global info
    global method_radio_button
    global blocked_user_input
    window = tk.Tk()
    # window initialisation
    window.geometry("350x250")
    window.winfo_toplevel().title("Tiktok scraper")

    # Hashtags label
    hashtags_label = tk.Label(text="Enter hashtags separated by commas like this ,")
    # Hashtag input
    hashtag_input = tk.Entry()
    # Minimum likes label
    likes_label = tk.Label(text="Minimum likes")
    # Minimum likes Input
    like_input = tk.Entry()
    # Minimum days label
    days_label = tk.Label(text="Specify the number of days allowed since video uploaded")
    # Minimum days Input
    days_input = tk.Entry()
    # Blocked user label
    blocked_user_label = tk.Label(text="Blocked user")
    # Blocked user input
    blocked_user_input = tk.Entry()
    method_radio_button = tk.IntVar()
    for_you = Radiobutton(window, text="For you", variable=method_radio_button, value=2,
                          )

    # Extract data button
    button = tk.Button(text="Extract videos", command=extract_videos)
    info = tk.Label(text="", fg='#0000CD')

    hashtags_label.pack()
    hashtag_input.pack()
    likes_label.pack()
    like_input.pack()
    days_label.pack()
    days_input.pack()

    by_hashtags = Radiobutton(window, text="By Hashtags", variable=method_radio_button, value=1,
                              )
    blocked_user_label.pack()
    blocked_user_input.pack()
    by_hashtags.pack()
    for_you.pack()
    button.pack(pady=10, side=tk.TOP)

    window.resizable(False, False)
    window.attributes("-topmost", True)
    method_radio_button.set(1)
    window.mainloop()
예제 #29
0
파일: YEDDA.py 프로젝트: sly461/YEDDA
 def body(self, master):
     """override"""
     box = Frame(master, relief='groove')
     self.scheme_var = StringVar(master, "BMES")
     Radiobutton(box, text="BMES", variable=self.scheme_var,
                 value="BMES").pack(side=LEFT, padx=5, pady=5)
     Radiobutton(box, text="BIO", variable=self.scheme_var,
                 value="BIO").pack(side=LEFT, padx=5, pady=5)
     box.pack()
     self.segmented_var = BooleanVar(master, self._guess_segmented())
     Checkbutton(master, text="Segmented",
                 variable=self.segmented_var).pack()
     self.only_NP_var = BooleanVar(master, False)
     Checkbutton(master, text="Only NP label",
                 variable=self.only_NP_var).pack()
     self.export_recommended_var = BooleanVar(master, True)
     Checkbutton(master,
                 text="Export Recommended",
                 variable=self.export_recommended_var).pack()
예제 #30
0
 def make_radiobuttons(self, name, labels=None):
     from tkinter import StringVar
     from tkinter.ttk import Radiobutton, Frame
     v = StringVar(self.widget_frame)
     v.set(labels[0])
     f = Frame(self.widget_frame, relief='groove', borderwidth=2)
     for label in labels:
         b = self._radiobuttons[name + label] = Radiobutton(f, variable=v, text=label, value=label)
         b.pack(anchor='w')
     f.pack()
     return TkWidgetWrapper(TkRbConsolidator(self._radiobuttons.values(), v))
예제 #31
0
    def __init__(self, Parent, *args, **kwargs):
        super().__init__() #constructor of super class
        self.Songs = [Song for Song in DirList('Songs') if Song.endswith('.mid')] #mappable songs
        self.MappedSongs = [Song for Song in DirList('MappedSongs') if Song.endswith('.cmid')] #mapped and compiled song

        TopLabel = Label(self, text = 'Compile a Song', font= CompilationScreen.Font(24), bd = 10) #top label with a title for the page
        TopLabel.place(anchor= 'n', relx= 0.5, rely = 0.015, relwidth = 1, relheight=0.15) #placing the label

        self.ItemList = ListBox(self) #item list of the song
        for Index, Item in enumerate(self.Songs): #for loop for every compiled comiled song
            self.ItemList.insert(Index, Item) #indexing the song in the list
            self.ItemList.itemconfig(Index, {'bg' : '#C2C2C2'})
        self.ItemList.place(anchor= 'n', relx= 0.5, rely = 0.19, relwidth = 1, relheight = 0.46) #placing the item list

        self.ApproxValue = IntVar()
        self.ApproxValue.set(1)
        self.SingleTracks = IntVar()
        self.SingleTracks.set(0)

        self.Closest = Radio(self, text = 'Closest Approximation (A# = A, A- = A)', variable = self.ApproxValue, value = 1)
        self.Closest.place(anchor = 'nw', relx = 0.008, rely = 0.65, relheight = 0.07, relwidth = 0.6)
        self.Upper = Radio(self, text = 'Upper Approximation (A# = B, A- = A)', variable = self.ApproxValue, value = 0)
        self.Upper.place(anchor = 'nw', relx = 0.008, rely = 0.71, relheight = 0.07, relwidth = 0.6)
        self.Split = Check(self, text = 'Split MIDI into single tracks', variable = self.SingleTracks, onvalue = 1, offvalue = 0)
        self.Split.place(anchor = 'nw', relx = 0.008, rely = 0.77, relheight = 0.07, relwidth = 0.6)

        self.Compilation = Button\
        (
            self,
            text = 'Compile selected song',
            command = lambda : self.CompileSong()
        )
        self.Compilation.place(anchor = 'nw', relx = 0.615, rely = 0.66, relheight = 0.17, relwidth = 0.38)

        self.Back = Button\
        (
            self,
            text = 'Back to Home',
            command = lambda : self.TurnBack()
        )
        self.Back.place(anchor = 'nw', relx = 0.008, rely = 0.84, relheight = 0.07, relwidth = 0.988)
예제 #32
0
 def add_item(self, label=None, **options):
     if self.inline:
         self.values.append(label)
         self.children.set_menu(*self.children)
     else:
         from tkinter.ttk import Radiobutton
         if not label is None:
             options.update(text=label, value=label)
         self.children.append(
             Radiobutton(self.widget,
                         variable=self.var,
                         command=self.callback,
                         **options))
         self.children[-1].pack(side="right", fill="both")
예제 #33
0
 def text_sen_config(self):
     '''创建单选框ASCII并配置单选框'''
     self.radiobutton_sen_variable = IntVar()  # 设置单选框variable变量,作用是规定value的数值类型
     self.button_sen_dx_acci = Radiobutton(master=self.text_sen_con)
     self.button_sen_dx_acci.config(
         text = 'ASCII',  # 单选框名字
         variable = self.radiobutton_sen_variable,  # 设置数值类型
         value = 1,  # 设置value数值,同一组单选框中数值必须不一样
         command = self.sen_ascii_set  # 绑定单选框单击之后调用的函数
     )
     '''创建单选框HEX并配置单选框'''
     self.button_sen_dx_hex = Radiobutton(master=self.text_sen_con)
     self.button_sen_dx_hex.config(
         text = 'HEX',  # 单选框名字
         variable = self.radiobutton_sen_variable,  # 设置数值类型
         value = 2,  # 设置value数值,同一组单选框中数值必须不一样
         command = self.sen_hex_set   # 绑定单选框单击之后调用的函数
     )
     self.radiobutton_sen_variable.set(1)  # 设置那个单选框初始的时候为选中状态
     self.button_sen_dx_acci.grid(padx=5,row=1, column=1, sticky='w')  # 封装ASCII单选框
     self.button_sen_dx_hex.grid(padx=5,row=1,column=2,sticky='e')  # 封装HEX单选框
     self.button_sen_clear_res = Button(master=self.text_sen_con,text='清空发送',command=lambda:self.clear_text(self.send_text))  # 添加清空接手区按键
     self.button_sen_clear_res.grid(row=2,sticky='s',columnspan=5,pady=7)  # 将清空按键打包
예제 #34
0
    def _create_frame_with_radio_btns(self, parent, name, text, row_index,
                                      column_index, add_both=True):
        ''' Creates frame with one set of Radiobuttons.

            Args:
                parent (Tk object): parent of the frame.
                name (str): name of the parameter that will a key in options
                    dictionary.
                text (list of str): list with two parameter values that should
                    be displayed next to the first two Radiobuttons.
                row_index (int): index of the row where the frame should
                    be placed using grid method.
                column_index (int): index of the column where the frame
                    should be placed using grid method.
                add_both (bool, optional): True if the third Radiobutton
                    with text "both" must be displayed, False otherwise,
                    defaults to True.
        '''
        assert len(text) == 2
        v = IntVar()
        self.options[name] = v
        self.options[name].trace(
            'w', (lambda *args: self.radio_btn_change(name)))
        frame_with_radio_btns = Frame(parent)
        first_option = Radiobutton(frame_with_radio_btns,
                                   text=text[0], variable=v, value=1)
        first_option.grid(row=0, column=0, sticky=W+N, padx=2)
        v.set(1)
        second_option = Radiobutton(frame_with_radio_btns,
                                    text=text[1], variable=v, value=2)
        second_option.grid(row=1, column=0, sticky=W+N, padx=2)
        if add_both:
            both = Radiobutton(frame_with_radio_btns, text='Both',
                               variable=v, value=3)
            both.grid(row=3, column=0, sticky=W+N, padx=2)
        frame_with_radio_btns.grid(row=row_index, column=column_index,
                                   padx=1, pady=5, sticky=W+N)
예제 #35
0
파일: gui.py 프로젝트: ixinshang/tz2txt
    def __init__(self, root):
        super().__init__(root)
        
        # url ============================
        self.url = StringVar()
        self.url.set(url_use)
        entry = Entry(self, textvariable=self.url,
                      bg='#666699', fg='#FFFFFF')
        entry.grid(row=0, column=0, columnspan=4, sticky=W+E)
        
        #==================================
        # 粘贴并打开
        self.paste_do = Button(self, text='处理网址', command=self.doit,
                               bg='#cc9933')
        self.paste_do.grid(row=1, column=0)
    
        # 状态
        self.status = Label(self, text='待机', fg='blue')
        self.status.grid(row=1, column=1)
        
        # 检查更新
        update_bt = Button(self, text='检测新版本', command=self.checkver)
        update_bt.grid(row=1, column=2)
        
        # 使用帮助
        help = Button(self, text='使用帮助', command=self.help_bt)
        help.grid(row=1, column=3)
        
        #================================
        
        # 辅助格式
        l4 = Label(self, text='辅助格式:')
        l4.grid(row=2, column=0)
        
        self.assist = IntVar()
        self.assist.set(2)
        
        r1 = Radiobutton(self, text='无辅助',
                         variable=self.assist, value=1)
        r1.grid(row=2, column=1)
        
        r2 = Radiobutton(self, text='页码模式',
                         variable=self.assist, value=2)
        r2.grid(row=2, column=2)
        
        self.r3 = Radiobutton(self, text='楼层模式',
                         variable=self.assist, value=3)
        self.r3.grid(row=2, column=3)
        
        # 末页
        l2 = Label(self, text='下载页数(-1为到末页):')
        l2.grid(row=3, column=0, columnspan=2, sticky=E)
        
        self.till = StringVar()
        self.till.set('-1')
        entry = Entry(self, textvariable=self.till, width=7)
        entry.grid(row=3, column=2)
        
        # 删除文件
        delfile = Button(self, text='删输出文件', command=self.delfile,
                         fg='#990000')
        delfile.grid(row=3, column=3)
        
        #====================================
        # 输出文件
        l3 = Label(self, text='输出文件:')
        l3.grid(row=4, column=0)
        
        self.output = StringVar()
        self.output.set('auto.txt')
        self.e_out = Entry(self, textvariable=self.output, width=10)
        self.e_out.grid(row=4, column=1)

        # 重命名
        self.rename = IntVar()
        self.rename.set(0)
        def callCheckbutton():
            v = self.rename.get()
            if v:
                self.e_out.config(state='disabled')
            else:
                self.e_out.config(state='normal')
            
        cb = Checkbutton(self,
                         variable=self.rename,
                         text='自动重命名',
                         command=callCheckbutton)
        cb.grid(row=4, column=2)
        
        # 覆盖
        self.override = IntVar()
        self.override.set(0)
        cb = Checkbutton(self,
                         variable=self.override,
                         text = '覆盖已有文件')
        cb.grid(row=4, column=3)
        
        #====================================
        
        # self
        self.pack()
        
        # fix radiobutton draw
        self.r3.focus_force()
        self.paste_do.focus_force()
예제 #36
0
def _gui():
  try:
    from tkinter import Tk, ttk, filedialog, messagebox, StringVar, IntVar
    from tkinter.ttk import Button, Entry, Frame, Label, LabelFrame, Notebook, Radiobutton, Style
  except:
    sys.exit("Unable to load tkinter. Aborting.")
  
  def _check_single(): #check the input and accordingly give the output... for the f_single tab
    if txt_f_single_entry.get()=="":
      lbl_f_single_result.config(text="", style="TLabel")
    elif check_afm(txt_f_single_entry.get()):
      lbl_f_single_result.config(text="Έγκυρο ΑΦΜ.", style="valid.TLabel")
    else:
      lbl_f_single_result.config(text="Άκυρο ΑΦΜ.", style="invalid.TLabel")
  
  def _select_input_file():
    strv_f_file_input.set(filedialog.askopenfilename(title="Άνοιγμα αρχείου"))
    if strv_f_file_input.get() != "" and strv_f_file_output.get() != "":
      btn_f_file_submit.config(state="normal")
    else: btn_f_file_submit.config(state="disabled")
#TODO a much better mechanism to enable / disable btn_f_file_submit is needed.
  def _select_output_file():
    strv_f_file_output.set(filedialog.asksaveasfilename(title="Αποθήκευση ως..."))
    if strv_f_file_input.get() != "" and strv_f_file_output.get() != "":
      btn_f_file_submit.config(state="normal")
    else: btn_f_file_submit.config(state="disabled")
  
  def _check_file():#TODO this could / should be merged with the TUI version...
    input_filepath = strv_f_file_input.get()
    output_filepath = strv_f_file_output.get()
    filter_output = intvar_filter_sel.get()
    try:
      input_file = open(input_filepath, "r")
      output_file = open(output_filepath, "w")
    except:
      messagebox.showerror(title="Σφάλμα", message="Αδυναμία διαχείρησης των αρχείων που ορίσατε.\n\nΠαρακαλώ επιβεβαιώστε πως το αρχείο με τα δεδομένα υπάρχει, πως έχετε δικαιώματα ανάγνωσης, και πως έχετε δικαιώματα εγγραφής στον κατάλογο εξαγωγής των αποτελεσμάτων.")
      return
    counter = {True:0, False:0}
    for entry in input_file:
      validation = check_afm(entry.strip())
      counter[validation]+=1
      if filter_output == 3 and validation == False:
        output_file.write(entry)
      elif filter_output == 2 and validation == True:
        output_file.write(entry)
      elif filter_output == 1:
        output_file.write(entry.strip() + "\t" + str(validation) + "\n\r")
    lbl_f_file_result.config(text="Σύνολο: "+str(counter[True]+counter[False])+"\nΈγκυρα: "+str(counter[True])+"\nΆκυρα: "+str(counter[False]))

  #create the window
  main_window = Tk()
  main_window.title("Έλεγχος εγκυρότητας Α.Φ.Μ. (v 2.0)")
  main_window.geometry("600x180")
  main_window.minsize(600,180)

  #fool arround with styling
  style = ttk.Style()
  style.configure("valid.TLabel", background="green")
  style.configure("empty.TLabel", background="white")
  style.configure("invalid.TLabel", background="red")
  style.configure("TNotebook", padding = 10)
  
  #create the Notebook
  tabs = Notebook(main_window)
  f_single = Frame(tabs)
  f_file = Frame(tabs)
  tabs.add(f_single, text="Μεμονομένα Α.Φ.Μ.")
  tabs.add(f_file, text="Λίστα από αρχείο")#add state="disabled" prior to git push until ready
  tabs.pack(anchor="nw")
  
  #add some widgets in f_single tab
  lbl_f_single_instructions = Label(f_single, text="Εισάγετε έναν ΑΦΜ για έλεγχο")
  lbl_f_single_instructions.grid(column=0, row=0)

  lbl_f_single_result = Label(f_single, text="", width=10, justify="center")
  lbl_f_single_result.grid(column=1, row=0, rowspan=2, sticky="ewns")

  txt_f_single_entry = Entry(f_single, width=11)
  txt_f_single_entry.focus()
  txt_f_single_entry.bind("<KeyRelease>", lambda e: _check_single() )
  txt_f_single_entry.grid(column=0,row=1)

  #btn_f_single_submit = Button(f_single, text="Έλεγχος", command=_check_single)
  #btn_f_single_submit.grid(column=0,row=2)
    
  #add some widgets in f_file tab
  lbl_f_file_finput = Label(f_file, text="Άνοιγμα...")
  lbl_f_file_finput.grid(column=0, row=0)
  strv_f_file_input = StringVar()
  txt_f_file_finput = Entry(f_file, textvariable = strv_f_file_input)
  txt_f_file_finput.grid(column=1, row=0)
  btn_f_file_finput = Button(f_file, text="...", width=3, command=_select_input_file)
  btn_f_file_finput.grid(column=2, row=0, sticky="W")
  
  lbl_f_file_foutput = Label(f_file, text="Αποθήκευση ως...")
  lbl_f_file_foutput.grid(column=0, row=1)
  strv_f_file_output = StringVar()
  txt_f_file_foutput = Entry(f_file, textvariable = strv_f_file_output)
  txt_f_file_foutput.grid(column=1, row=1)
  btn_f_file_foutput = Button(f_file, text="...", width=3, command=_select_output_file)
  btn_f_file_foutput.grid(column=2, row=1, sticky="W")
  
  lf_filter = LabelFrame(f_file, text="Επιστροφή")
  lf_filter.grid(column=3, row=0, rowspan=2, sticky="ewns")
  intvar_filter_sel = IntVar()
  rb_filter_all = Radiobutton(lf_filter, text="Όλων", variable=intvar_filter_sel, value=1) #TODO maybe add command
  rb_filter_all.pack(anchor="w")
  rb_filter_all.invoke()
  rb_filter_true = Radiobutton(lf_filter, text="Έγκυρων", variable=intvar_filter_sel, value=2)
  rb_filter_true.pack(anchor="w")
  rb_filter_false = Radiobutton(lf_filter, text="Άκυρων", variable=intvar_filter_sel, value=3)
  rb_filter_false.pack(anchor="w")
  
  lf_result = LabelFrame(f_file, text="Σύνοψη")
  lf_result.grid(column=4, row=0, rowspan=2, sticky="ewns")
  lbl_f_file_result = Label(lf_result, text="", width=12)#TODO bring results
  lbl_f_file_result.pack()
  
  btn_f_file_submit = Button(f_file, text="Επεξεργασία", state="disabled", command=_check_file)
  btn_f_file_submit.grid(column=0, row=2, columnspan=3)
  
  btn_main_exit = Button(main_window, text="Έξοδος", command=sys.exit)
  btn_main_exit.pack(anchor="se")

  main_window.mainloop()
예제 #37
0
class ModelFrame(LabelFrame):
	
	topPadding = 12

	def __init__(self,parent):        
		LabelFrame.__init__(self,parent,text="Model",borderwidth=5)
		
		self.selection = tkinter.IntVar()
		
		self.exponential = Radiobutton(self,text="Exponential model",variable=self.selection,value=Model.EXP.value,command=self.changeSelection)
		self.powerlaw = Radiobutton(self,text="Power law model",variable=self.selection,value=Model.POW.value,command=self.changeSelection)
		self.weibull = Radiobutton(self,text="Weibull model",variable=self.selection,value=Model.WEI.value,command=self.changeSelection)

		self.exponential.grid(row=0,column=0,sticky="W",padx=10,pady=(self.topPadding,5))
		self.powerlaw.grid(row=1,column=0,sticky="W",padx=10,pady=5)
		self.weibull.grid(row=2,column=0,sticky="W",padx=10,pady=(5,0))
		
		seperator = Separator(self, orient=tkinter.VERTICAL)
		seperator.grid(row=0, column=1, rowspan=3, sticky="NS", padx=(20,10), pady=(self.topPadding,0))
		
		## Exponential setup

		self.expNumberOfSegments_L = Label(self,text="Number of segments: ")
		self.expNumberOfSegments_E = Entry(self,width=5, justify="right")

		self.expNumberOfSegments_E.insert(0, settings.EXP_DEFAULT_NUMBER_OF_SEGMENTS)

		self.expWidgets = [self.expNumberOfSegments_L,self.expNumberOfSegments_E]
		
		## Power law setup

		self.powProximalLimit_L = Label(self,text="Proximal limit of integration: ")
		self.powProximalLimit_E = Entry(self,width=5, justify="right")
		self.powDistalLimit_L = Label(self,text="Distal limit of integration: ")
		self.powDistalLimit_E = Entry(self,width=5, justify="right")

		self.powProximalLimit_E.insert(0, settings.POW_DEFAULT_PROXIMAL_LIMIT)
		self.powDistalLimit_E.insert(0, settings.POW_DEFAULT_DISTAL_LIMIT)

		self.powWidgets = [self.powProximalLimit_L,self.powProximalLimit_E,
						   self.powDistalLimit_L,self.powDistalLimit_E]
		
		## Weibull setup

		self.weiNumberOfRuns_L = Label(self,text="Number of runs: ")
		self.weiNumberOfRuns_E = Entry(self,width=5, justify="right")
		self.weiIterationsPerRun_L = Label(self,text="Iterations per run: ")
		self.weiIterationsPerRun_E = Entry(self,width=5, justify="right")

		self.weiEstimatedTime_L = Label(self,text="Estimated time (s): ")
		self.weiEstimatedTime_E = CustomEntry(self,width=5, justify="right")
		self.weiEstimatedTime_E.setUserEditable(False)

		self.weiLambdaLowerBoundL = Label(self,text="\u03BB lower bound:")
		self.weiLambdaUpperBoundL = Label(self,text="\u03BB upper bound:")
		self.weiLambdaLowerBoundE = Entry(self,width=5, justify="right")
		self.weiLambdaUpperBoundE = Entry(self,width=5, justify="right")

		self.weiKLowerBoundL = Label(self,text="k lower bound:")
		self.weiKUpperBoundL = Label(self,text="k upper bound:")
		self.weiKLowerBoundE = Entry(self,width=5, justify="right")
		self.weiKUpperBoundE = Entry(self,width=5, justify="right")

		self.weiNumberOfRuns_E.insert(0, settings.WEI_DEFAULT_NUMBER_OF_RUNS)
		self.weiIterationsPerRun_E.insert(0, settings.WEI_DEFAULT_ITERATIONS_PER_RUN)
		self.weiLambdaLowerBoundE.insert(0, settings.WEI_DEFAULT_LAMBDA_LOWER_BOUND)
		self.weiLambdaUpperBoundE.insert(0, settings.WEI_DEFAULT_LAMBDA_UPPER_BOUND)
		self.weiKLowerBoundE.insert(0, settings.WEI_DEFAULT_K_LOWER_BOUND)
		self.weiKUpperBoundE.insert(0, settings.WEI_DEFAULT_K_UPPER_BOUND)

		
		self.weiWidgets = [self.weiNumberOfRuns_L,self.weiNumberOfRuns_E,
						   self.weiIterationsPerRun_L,self.weiIterationsPerRun_E,
						   self.weiEstimatedTime_L,self.weiEstimatedTime_E,
						   self.weiLambdaLowerBoundL,self.weiLambdaUpperBoundL,self.weiLambdaLowerBoundE,self.weiLambdaUpperBoundE,
						   self.weiKLowerBoundL,self.weiKUpperBoundL,self.weiKLowerBoundE,self.weiKUpperBoundE]
		
		## General

		self.currentWidgets = []
		self.selection.set(Model.EXP.value)
		self.changeSelection()
		
	def changeSelection(self):
		
		for widget in self.currentWidgets:
			widget.grid_remove()

		modelType = Model(self.selection.get())
		
		sX = 10
		bX = 20
		
		if modelType == Model.EXP:
			self.expNumberOfSegments_L.grid(row=0,column=2,padx=(bX,sX),pady=(self.topPadding,5),sticky="W")
			self.expNumberOfSegments_E.grid(row=0,column=3,padx=(sX,bX),pady=(self.topPadding,5),sticky="W")
			self.currentWidgets = self.expWidgets
		elif modelType == Model.POW:
			self.powProximalLimit_L.grid(row=0,column=2,padx=(bX,sX),pady=(self.topPadding,5),sticky="W")
			self.powProximalLimit_E.grid(row=0,column=3,padx=(sX,bX),pady=(self.topPadding,5),sticky="W")
			self.powDistalLimit_L.grid(row=1,column=2,padx=(bX,sX),pady=5,sticky="W")
			self.powDistalLimit_E.grid(row=1,column=3,padx=(sX,bX),pady=5,sticky="W")
			self.currentWidgets = self.powWidgets
		elif modelType == Model.WEI:
			self.weiNumberOfRuns_L.grid(row=0,column=2,padx=(bX,sX),pady=(self.topPadding,5),sticky="W")
			self.weiNumberOfRuns_E.grid(row=0,column=3,padx=(sX,bX),pady=(self.topPadding,5),sticky="W")
			self.weiIterationsPerRun_L.grid(row=1,column=2,padx=(bX,sX),pady=5,sticky="W")
			self.weiIterationsPerRun_E.grid(row=1,column=3,padx=(sX,bX),pady=5,sticky="W")
			self.weiEstimatedTime_L.grid(row=2,column=2,padx=(bX,sX),pady=5,sticky="W")
			self.weiEstimatedTime_E.grid(row=2,column=3,padx=(sX,bX),pady=5,sticky="W")
			
			self.weiLambdaLowerBoundL.grid(row=0,column=4,padx=(bX,sX),pady=(self.topPadding,5),sticky="W")
			self.weiLambdaLowerBoundE.grid(row=0,column=5,padx=(sX,bX),pady=(self.topPadding,5))
			self.weiLambdaUpperBoundL.grid(row=1,column=4,padx=(bX,sX),pady=5,sticky="W")
			self.weiLambdaUpperBoundE.grid(row=1,column=5,padx=(sX,bX),pady=5)
			
			self.weiKLowerBoundL.grid(row=0,column=6,padx=(bX,sX),pady=(self.topPadding,5),sticky="W")
			self.weiKLowerBoundE.grid(row=0,column=7,padx=(sX,sX),pady=(self.topPadding,5))
			self.weiKUpperBoundL.grid(row=1,column=6,padx=(bX,sX),pady=5,sticky="W")
			self.weiKUpperBoundE.grid(row=1,column=7,padx=(sX,sX),pady=5)
			
			self.currentWidgets = self.weiWidgets
	
	def getModelDetails(self):
		modelType = Model(self.selection.get())
		values = [modelType]

		if modelType == Model.EXP:
			numberOfSegments = helper_functions.validateValue(
									self.expNumberOfSegments_E.get(),
									"The number of exponential segments must be 1 \u2264 n \u2264 " + str(settings.EXP_MAX_NUMBER_OF_SEGMENTS),
									"int",
									lowerBound=1,
									upperBound=settings.EXP_MAX_NUMBER_OF_SEGMENTS)
			values.append(numberOfSegments)
			
		elif modelType == Model.POW:
			proximalLimitKM = helper_functions.validateValue(
									self.powProximalLimit_E.get(),
									"The proximal limit of integration must be 0 \u2264 x \u2264 \u221E",
									"float",
									strictLowerBound=0,
									strictUpperBound=float('inf'))
			proximalLimitKM /= SQRT_PI
			
			distalLimitKM = helper_functions.validateValue(
									self.powDistalLimit_E.get(),
									"The distal limit of integration must be prox \u2264 x \u2264 \u221E",
									"float",
									strictLowerBound=proximalLimitKM,
									strictUpperBound=float('inf'))
			distalLimitKM /= SQRT_PI
			
			values.extend([proximalLimitKM,distalLimitKM])
			
		elif modelType == Model.WEI:
			numberOfRuns = helper_functions.validateValue(
									self.weiNumberOfRuns_E.get(),
									"The number of runs must be greater than 0",
									"int",
									strictLowerBound=0)
			
			iterationsPerRun = helper_functions.validateValue(
									self.weiIterationsPerRun_E.get(),
									"The number of iterations must be greater than 0",
									"int",
									strictLowerBound=0)
			
			lambdaLowerBound = helper_functions.validateValue(
									self.weiLambdaLowerBoundE.get(),
									"The lower bound for \u03BB must be a decimal",
									"float")
			  
			lambdaUpperBound = helper_functions.validateValue(
									self.weiLambdaUpperBoundE.get(),
									"The upper bound for \u03BB must be greater than the lower bound",
									"float",
									strictLowerBound=lambdaLowerBound)
			
			kLowerBound = helper_functions.validateValue(
									self.weiKLowerBoundE.get(),
									"The lower bound for k must be numeric and less than 2",
									"float",
									strictUpperBound=2)
												
			kUpperBound = helper_functions.validateValue(
									self.weiKUpperBoundE.get(),
									"The upper bound for k must be greater than the lower bound and less than or equal to 2",
									"float",
									strictLowerBound=kLowerBound,
									upperBound=2)
			
			values.extend([numberOfRuns,iterationsPerRun,[[lambdaLowerBound,lambdaUpperBound],[kLowerBound,kUpperBound]]])
		
		return values
예제 #38
0
 def __make_radio(dialog, v):
     radio = Radiobutton(dialog, image=tk_image, variable=v, value=index)
     radio.grid(row=row, column=column)
     return radio
예제 #39
0
	def __init__(self,parent):        
		LabelFrame.__init__(self,parent,text="Model",borderwidth=5)
		
		self.selection = tkinter.IntVar()
		
		self.exponential = Radiobutton(self,text="Exponential model",variable=self.selection,value=Model.EXP.value,command=self.changeSelection)
		self.powerlaw = Radiobutton(self,text="Power law model",variable=self.selection,value=Model.POW.value,command=self.changeSelection)
		self.weibull = Radiobutton(self,text="Weibull model",variable=self.selection,value=Model.WEI.value,command=self.changeSelection)

		self.exponential.grid(row=0,column=0,sticky="W",padx=10,pady=(self.topPadding,5))
		self.powerlaw.grid(row=1,column=0,sticky="W",padx=10,pady=5)
		self.weibull.grid(row=2,column=0,sticky="W",padx=10,pady=(5,0))
		
		seperator = Separator(self, orient=tkinter.VERTICAL)
		seperator.grid(row=0, column=1, rowspan=3, sticky="NS", padx=(20,10), pady=(self.topPadding,0))
		
		## Exponential setup

		self.expNumberOfSegments_L = Label(self,text="Number of segments: ")
		self.expNumberOfSegments_E = Entry(self,width=5, justify="right")

		self.expNumberOfSegments_E.insert(0, settings.EXP_DEFAULT_NUMBER_OF_SEGMENTS)

		self.expWidgets = [self.expNumberOfSegments_L,self.expNumberOfSegments_E]
		
		## Power law setup

		self.powProximalLimit_L = Label(self,text="Proximal limit of integration: ")
		self.powProximalLimit_E = Entry(self,width=5, justify="right")
		self.powDistalLimit_L = Label(self,text="Distal limit of integration: ")
		self.powDistalLimit_E = Entry(self,width=5, justify="right")

		self.powProximalLimit_E.insert(0, settings.POW_DEFAULT_PROXIMAL_LIMIT)
		self.powDistalLimit_E.insert(0, settings.POW_DEFAULT_DISTAL_LIMIT)

		self.powWidgets = [self.powProximalLimit_L,self.powProximalLimit_E,
						   self.powDistalLimit_L,self.powDistalLimit_E]
		
		## Weibull setup

		self.weiNumberOfRuns_L = Label(self,text="Number of runs: ")
		self.weiNumberOfRuns_E = Entry(self,width=5, justify="right")
		self.weiIterationsPerRun_L = Label(self,text="Iterations per run: ")
		self.weiIterationsPerRun_E = Entry(self,width=5, justify="right")

		self.weiEstimatedTime_L = Label(self,text="Estimated time (s): ")
		self.weiEstimatedTime_E = CustomEntry(self,width=5, justify="right")
		self.weiEstimatedTime_E.setUserEditable(False)

		self.weiLambdaLowerBoundL = Label(self,text="\u03BB lower bound:")
		self.weiLambdaUpperBoundL = Label(self,text="\u03BB upper bound:")
		self.weiLambdaLowerBoundE = Entry(self,width=5, justify="right")
		self.weiLambdaUpperBoundE = Entry(self,width=5, justify="right")

		self.weiKLowerBoundL = Label(self,text="k lower bound:")
		self.weiKUpperBoundL = Label(self,text="k upper bound:")
		self.weiKLowerBoundE = Entry(self,width=5, justify="right")
		self.weiKUpperBoundE = Entry(self,width=5, justify="right")

		self.weiNumberOfRuns_E.insert(0, settings.WEI_DEFAULT_NUMBER_OF_RUNS)
		self.weiIterationsPerRun_E.insert(0, settings.WEI_DEFAULT_ITERATIONS_PER_RUN)
		self.weiLambdaLowerBoundE.insert(0, settings.WEI_DEFAULT_LAMBDA_LOWER_BOUND)
		self.weiLambdaUpperBoundE.insert(0, settings.WEI_DEFAULT_LAMBDA_UPPER_BOUND)
		self.weiKLowerBoundE.insert(0, settings.WEI_DEFAULT_K_LOWER_BOUND)
		self.weiKUpperBoundE.insert(0, settings.WEI_DEFAULT_K_UPPER_BOUND)

		
		self.weiWidgets = [self.weiNumberOfRuns_L,self.weiNumberOfRuns_E,
						   self.weiIterationsPerRun_L,self.weiIterationsPerRun_E,
						   self.weiEstimatedTime_L,self.weiEstimatedTime_E,
						   self.weiLambdaLowerBoundL,self.weiLambdaUpperBoundL,self.weiLambdaLowerBoundE,self.weiLambdaUpperBoundE,
						   self.weiKLowerBoundL,self.weiKUpperBoundL,self.weiKLowerBoundE,self.weiKUpperBoundE]
		
		## General

		self.currentWidgets = []
		self.selection.set(Model.EXP.value)
		self.changeSelection()
예제 #40
0
파일: test.py 프로젝트: Exodus111/Projects
###### Start Tkinter #####
root = Tk()

###### Init our variables ###
myint = IntVar()
mystring = StringVar()

###### Make our Widgets ####
main_frame = Frame(root)
top_frame = Frame(main_frame)
mid_frame = Frame(main_frame)
bottom_frame = Frame(main_frame)

label = Label(top_frame, text="This is my Label")
entry = Entry(top_frame, textvariable=mystring)
radio = Radiobutton(top_frame, text="Enable", variable=myint, value=1)

text1 = Text(mid_frame)
text2 = Text(mid_frame)

ok_button = Button(bottom_frame, text="Ok", command=okbutton)
cancel_button = Button(bottom_frame, text="Cancel", command=exit)

###### Pack our Widgets #######
main_frame.pack()
top_frame.pack()
mid_frame.pack()
bottom_frame.pack(anchor="e")

label.pack(side="left")
entry.pack(side="left")
예제 #41
0
class MarkovDemo(Frame):

    "MarkovDemo(master=None, **kw) -> MarkovDemo instance"

    TEXT = dict(height=2, width=46, wrap=WORD)  # Text Options
    GRID = dict(padx=5, pady=5)                 # Grid Options

    # Initialize a MarkovDemo instance with a GUI for interaction.

    def __init__(self, master=None, **kw):
        "Initialize the MarkovDemo instance's widgets and settings."
        super().__init__(master, **kw)
        self.build_widgets()
        self.place_widgets()
        self.setup_widgets()
        self.grid_rowconfigure(2, weight=1)
        self.grid_rowconfigure(3, weight=1)
        self.grid_columnconfigure(0, weight=1)
        self.key = self.primer = None

    def build_widgets(self):
        "Build the various widgets that will be used in the program."
        # Create processing frame widgets.
        self.processing_frame = LabelFrame(self, text='Processing Mode:')
        self.mode_var = StringVar(self, 'encode')
        self.decode_button = Radiobutton(self.processing_frame,
                                         text='Decode Cipher-Text',
                                         command=self.handle_radiobuttons,
                                         value='decode',
                                         variable=self.mode_var)
        self.encode_button = Radiobutton(self.processing_frame,
                                         text='Encode Plain-Text',
                                         command=self.handle_radiobuttons,
                                         value='encode',
                                         variable=self.mode_var)
        self.freeze_var = BooleanVar(self, False)
        self.freeze_button = Checkbutton(self.processing_frame,
                                         text='Freeze Key & Primer',
                                         command=self.handle_checkbutton,
                                         offvalue=False,
                                         onvalue=True,
                                         variable=self.freeze_var)
        # Create encoding frame widgets.
        self.encoding_frame = LabelFrame(self, text='Encoding Options:')
        self.chain_size_label = Label(self.encoding_frame, text='Chain Size:')
        self.chain_size_entry = Entry(self.encoding_frame)
        self.plain_text_label = Label(self.encoding_frame, text='Plain-Text:')
        self.plain_text_entry = Entry(self.encoding_frame)
        # Create input frame widgets.
        self.input_frame = LabelFrame(self, text='Input Area:')
        self.input_text = ScrolledText(self.input_frame, **self.TEXT)
        # Create output frame widgets.
        self.output_frame = LabelFrame(self, text='Output Area:')
        self.output_text = ScrolledText(self.output_frame, **self.TEXT)

    def place_widgets(self):
        "Place the widgets where they belong in the MarkovDemo frame."
        # Locate processing frame widgets.
        self.processing_frame.grid(sticky=EW, **self.GRID)
        self.decode_button.grid(row=0, column=0, **self.GRID)
        self.encode_button.grid(row=0, column=1, **self.GRID)
        self.freeze_button.grid(row=0, column=2, **self.GRID)
        # Locate encoding frame widgets.
        self.encoding_frame.grid(sticky=EW, **self.GRID)
        self.chain_size_label.grid(row=0, column=0, sticky=W, **self.GRID)
        self.chain_size_entry.grid(row=0, column=1, sticky=EW, **self.GRID)
        self.plain_text_label.grid(row=1, column=0, sticky=W, **self.GRID)
        self.plain_text_entry.grid(row=1, column=1, sticky=EW, **self.GRID)
        self.encoding_frame.grid_columnconfigure(1, weight=1)
        # Locate input frame widgets.
        self.input_frame.grid(sticky=NSEW, **self.GRID)
        self.input_text.grid(sticky=NSEW, **self.GRID)
        self.input_frame.grid_rowconfigure(0, weight=1)
        self.input_frame.grid_columnconfigure(0, weight=1)
        # Locate output frame widgets.
        self.output_frame.grid(sticky=NSEW, **self.GRID)
        self.output_text.grid(sticky=NSEW, **self.GRID)
        self.output_frame.grid_rowconfigure(0, weight=1)
        self.output_frame.grid_columnconfigure(0, weight=1)

    def setup_widgets(self):
        "Setup each widget's configuration for the events they handle."
        self.input_text.bind('<Key>', self.handle_key_events)
        self.input_text.bind('<Control-Key-a>', self.handle_control_a)
        self.input_text.bind('<Control-Key-/>', lambda event: 'break')
        self.output_text['state'] = DISABLED
        self.output_text.bind('<Control-Key-a>', self.handle_control_a)
        self.output_text.bind('<Control-Key-/>', lambda event: 'break')

    ########################################################################

    # Take care of any special event needing dedicated processing.

    def handle_radiobuttons(self):
        "Change the interface based on the encoding / decoding setting."
        if self.encrypting:
            self.freeze_button.grid()
            if not self.freeze_var.get():
                self.encoding_frame.grid()
        else:
            self.freeze_button.grid_remove()
            if not self.freeze_var.get():
                self.encoding_frame.grid_remove()
        self.handle_key_events(None)

    def handle_checkbutton(self):
        "Change the interface based on the key / primer freeze setting."
        if self.freeze_var.get():
            self.encoding_frame.grid_remove()
        else:
            self.encoding_frame.grid()

    def handle_key_events(self, event):
        "Schedule refreshing the output area after an input area event."
        if event is None or event.char and event.state | 0o11 == 0o11:
            self.after_idle(self.refresh)

    @staticmethod
    def handle_control_a(event):
        "Select all text in the widget associated with the given event."
        event.widget.tag_add(SEL, 1.0, END + '-1c')
        return 'break'

    ########################################################################

    # Handle interface's updates when either encoding or decoding.

    def refresh(self):
        "Refresh the output based on the value of the input."
        text = self.input_text.get(1.0, END + '-1c')
        if not text:
            self.output = text
        elif self.encrypting:
            self.encode(text)
        else:
            self.decode(text)

    def output(self, value):
        "Set the text in the output area to the string value."
        self.output_text['state'] = NORMAL
        self.output_text.delete(1.0, END)
        self.output_text.insert(END, value)
        if self.encrypting and self.freeze_var.get():
            self.output_text.see(END)
        self.output_text['state'] = DISABLED

    output = property(fset=output, doc='Output area property.')

    @property
    def chain_size(self):
        "Chain size for the Markov chains used when encrypting."
        try:
            value = ast.literal_eval(self.chain_size_entry.get())
            assert isinstance(value, int) and 2 <= value <= 256
            return value
        except:
            self.chain_size_entry.delete(0, END)
            self.chain_size_entry.insert(0, '2')
            return 2

    @property
    def plain_text(self):
        "Plain text or ignored characters in encryption process."
        try:
            value = self.repr_to_obj(self.plain_text_entry.get(), '')
            assert isinstance(value, str)
            return value
        except:
            self.plain_text_entry.delete(0, END)
            return ''

    ########################################################################

    # Encrypt a string for display in the interface's output area.

    def encode(self, string):
        "Encode the string and show the cipher-text in the output."
        try:
            cipher = self.build_cipher(string)
        except ValueError:
            self.output = ''
        except:
            self.output = traceback.format_exc()
        else:
            self.output = self.build_header() + '\n\n' + cipher

    def build_cipher(self, string):
        "Build cipher-text based on plain-text and return answer."
        if self.key and self.freeze_var.get():
            cipher, primer = me.encrypt_str(string, self.key, self.primer)
        else:
            args = string, self.chain_size, self.plain_text
            cipher, self.key, self.primer = me.auto_encrypt_str(*args)
        return cipher

    def build_header(self):
        "Build header from key and primer values in current use."
        header = '\n'.join(map(self.bytes_to_repr, self.key.data))
        header += '\n' + self.bytes_to_repr(self.primer.data)
        return header

    ########################################################################

    # Decrypt a string for display in the interface's output area.

    def decode(self, string):
        "Decode encrypted message and display plain-text in output."
        try:
            cipher = self.extract_keys(string)
            text = self.extract_text(cipher)
        except ValueError:
            self.output = ''
        except:
            self.output = traceback.format_exc()
        else:
            self.output = text

    def extract_keys(self, string):
        "Extract keys to decryption and return the cipher-text area."
        header, cipher = string.split('\n\n', 1)
        *key, primer = map(self.repr_to_obj, header.split('\n'))
        self.key, self.primer = me.Key(tuple(key)), me.Primer(primer)
        return cipher

    def extract_text(self, string):
        "Extract text message from string using built key and primer."
        text, primer = me.decrypt_str(string, self.key, self.primer)
        return text

    ########################################################################

    # Provide some special methods to simplify the program's code.

    @property
    def encrypting(self):
        "Encrypting boolean stating current operations mode."
        return {'encode': True, 'decode': False}[self.mode_var.get()]

    @staticmethod
    def bytes_to_repr(obj):
        "Convert bytes object into suitable representation."
        if not isinstance(obj, bytes):
            raise TypeError('Object must be a bytes instance!')
        return repr(obj)[2:-1]

    @staticmethod
    def repr_to_obj(string, prefix='b'):
        "Convert representation into an equivalent object."
        for template in '{}"{}"', "{}'{}'":
            try:
                return ast.literal_eval(template.format(prefix, string))
            except:
                pass
        raise ValueError('Cannot convert {!r} to object!'.format(string))

    @classmethod
    def main(cls):
        "Create context for demo and run a test instance."
        NoDefaultRoot()
        root = Tk()
        root.minsize(420, 330)
        root.title('Markov Demo 2')
        test = cls(root)
        test.grid(sticky=NSEW)
        root.grid_rowconfigure(0, weight=1)
        root.grid_columnconfigure(0, weight=1)
        root.mainloop()
예제 #42
0
파일: gui.py 프로젝트: ixinshang/tz2txt
class Gui(Frame):
    def __init__(self, root):
        super().__init__(root)
        
        # url ============================
        self.url = StringVar()
        self.url.set(url_use)
        entry = Entry(self, textvariable=self.url,
                      bg='#666699', fg='#FFFFFF')
        entry.grid(row=0, column=0, columnspan=4, sticky=W+E)
        
        #==================================
        # 粘贴并打开
        self.paste_do = Button(self, text='处理网址', command=self.doit,
                               bg='#cc9933')
        self.paste_do.grid(row=1, column=0)
    
        # 状态
        self.status = Label(self, text='待机', fg='blue')
        self.status.grid(row=1, column=1)
        
        # 检查更新
        update_bt = Button(self, text='检测新版本', command=self.checkver)
        update_bt.grid(row=1, column=2)
        
        # 使用帮助
        help = Button(self, text='使用帮助', command=self.help_bt)
        help.grid(row=1, column=3)
        
        #================================
        
        # 辅助格式
        l4 = Label(self, text='辅助格式:')
        l4.grid(row=2, column=0)
        
        self.assist = IntVar()
        self.assist.set(2)
        
        r1 = Radiobutton(self, text='无辅助',
                         variable=self.assist, value=1)
        r1.grid(row=2, column=1)
        
        r2 = Radiobutton(self, text='页码模式',
                         variable=self.assist, value=2)
        r2.grid(row=2, column=2)
        
        self.r3 = Radiobutton(self, text='楼层模式',
                         variable=self.assist, value=3)
        self.r3.grid(row=2, column=3)
        
        # 末页
        l2 = Label(self, text='下载页数(-1为到末页):')
        l2.grid(row=3, column=0, columnspan=2, sticky=E)
        
        self.till = StringVar()
        self.till.set('-1')
        entry = Entry(self, textvariable=self.till, width=7)
        entry.grid(row=3, column=2)
        
        # 删除文件
        delfile = Button(self, text='删输出文件', command=self.delfile,
                         fg='#990000')
        delfile.grid(row=3, column=3)
        
        #====================================
        # 输出文件
        l3 = Label(self, text='输出文件:')
        l3.grid(row=4, column=0)
        
        self.output = StringVar()
        self.output.set('auto.txt')
        self.e_out = Entry(self, textvariable=self.output, width=10)
        self.e_out.grid(row=4, column=1)

        # 重命名
        self.rename = IntVar()
        self.rename.set(0)
        def callCheckbutton():
            v = self.rename.get()
            if v:
                self.e_out.config(state='disabled')
            else:
                self.e_out.config(state='normal')
            
        cb = Checkbutton(self,
                         variable=self.rename,
                         text='自动重命名',
                         command=callCheckbutton)
        cb.grid(row=4, column=2)
        
        # 覆盖
        self.override = IntVar()
        self.override.set(0)
        cb = Checkbutton(self,
                         variable=self.override,
                         text = '覆盖已有文件')
        cb.grid(row=4, column=3)
        
        #====================================
        
        # self
        self.pack()
        
        # fix radiobutton draw
        self.r3.focus_force()
        self.paste_do.focus_force()
    
    def doit(self):
        # 获取、显示网址
        try:
            u = self.master.clipboard_get().strip()
        except:
            bad = True
            u = ''
        else:
            bad = False

        if bad or not tz2txt.is_url(u):
            self.url.set('无效网址,网址须以http://或https://开头。')
            return
        self.url.set(u)
        
        # 辅助模式
        assist = self.assist.get()
        if assist == 1:
            label = ''
        elif assist == 2:
            label = 'page'
        elif assist == 3:
            label = 'floor'
            
        # 末页
        till = self.till.get().strip()
        try:
            till = int(till)
        except:
            till = -1
        
        # 执行命令
        self.status['fg'] = '#993300'
        self.status['text'] = '处理中'
        self.update()
        
        # except里return
        try:
            output, discard_output, title, info_list, chinese_ct = \
                tz2txt.auto(u, till, '', '', label, from_gui=True)
            if title == None:
                raise Exception('无法完成全自动处理')
        
        except Exception as e:
            print('\n出现异常:', e)
            print('===================================\n')            
            return
        
        else:
            # 显示标题
            title = red.sub(r'[\U00010000-\U0010FFFF]', r'', title)
            title = title.strip()
            self.url.set(title)
        
        finally:
            self.status['fg'] = 'blue'
            self.status['text'] = '待机'
                    
        # 输出文件名
        if self.rename.get():
            output_fn = title + '.txt'
        else:
            output_fn = self.output.get().strip()
        
        # 合法文件名
        output_fn = red.sub(r'[\\/:*?"<>|]', r'', output_fn)
        if output_fn == '.txt':
            output_fn = '楼主.txt'
        
        # 输出内容
        text = output.getvalue()
        output.close()
            
        # 覆盖判断:文件已存在 and 输出有内容 and (强制覆盖 or 选择覆盖)
        if os.path.isfile(output_fn) and \
           text and \
           (self.override.get() == 1 or \
            messagebox.askyesno('输出文件已存在', '是否覆盖?\n%s' % output_fn)
            ):
            # 删除已有目标
            try:
                os.remove(output_fn)
            except:
                pass
        
        # 写入output
        if not os.path.isfile(output_fn) and text:
            try:
                with open(output_fn, 'w', 
                          encoding='gb18030', errors='replace') as f:
                    f.write(text)
                print('\n已保存为:', output_fn)
            except Exception as e:
                print('\n保存文件时出现异常', e)
        
            # 显示信息 
            size2 = os.path.getsize(output_fn)
            size2 = format(size2, ',')
            chinese_ct = format(chinese_ct, ',')
            print('输出文件 {0} 字节,约 {1} 个汉字。'.format(
                                                        size2,
                                                        chinese_ct)
                  )
                
        # 写入discard
        if discard_output != None:
            try:
                text = discard_output.getvalue()
                discard_output.close()
                
                if text:
                    with open(discard_fn, 'w', 
                              encoding='gb18030', errors='replace') as f:
                        f.write(text)
            except Exception as e:
                print('\n保存文件时出现异常', e)

        print()
        for line in info_list:
            if line.startswith('下载时间:'):
                break
            datamachine.save_print(line.rstrip('\n'))
        print('===================================\n')

        
    def delfile(self):
        try:
            output = self.output.get().strip()
            os.remove(output)
        except:
            pass
        else:
            print('已删除输出文件')
        
        try:
            os.remove(discard_fn)
        except:
            pass
        else:
            print('已删除丢弃文件')
        
        self.url.set(url_use)
        
    def checkver(self):
        self.status['fg'] = '#993300'
        self.status['text'] = '处理中'
        self.update()
        
        print('当前版本:', tz2txt.tz2txt_date)
        
        try:
            newver, download_url = checkver.check()
        except Exception as e:
            print('出现异常:', e)
        else:
            if newver > tz2txt.tz2txt_date:
                print('发现新版本:', newver)
                if messagebox.askyesno('发现新版本', 
                        '最新版本:%s\n是否用浏览器打开下载网址?' % newver):
                    try:
                        webbrowser.open_new_tab(download_url)
                    except:
                        print('无法用浏览器打开下载网址:', download_url)
            elif newver != tz2txt.tz2txt_date:
                print('当前版本比网盘版本(%s)新' % newver)
            else:
                print('检查完毕,没有发现新版本')
            print()
        
        self.status['fg'] = 'blue'
        self.status['text'] = '待机'
        
    def help_bt(self):
        url = 'http://www.cnblogs.com/animalize/p/4770397.html'
        try:
            webbrowser.open_new_tab(url)
        except:
            print('无法用浏览器打开使用帮助,网址:', url)