本文整理汇总了Python中tkinter.Button.configure方法的典型用法代码示例。如果您正苦于以下问题:Python Button.configure方法的具体用法?Python Button.configure怎么用?Python Button.configure使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tkinter.Button
的用法示例。
在下文中一共展示了Button.configure方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from tkinter import Button [as 别名]
# 或者: from tkinter.Button import configure [as 别名]
def __init__(self, parent, buttondefs):
'''Initialization method.'''
Frame.__init__(self, parent)
for title, handler in buttondefs:
new_button = Button(self, text=title)
cmd = lambda callback=handler, button=new_button: callback(button)
new_button.configure(command=cmd)
new_button.pack(side=LEFT, padx=5, pady=5)
示例2: AddManually
# 需要导入模块: from tkinter import Button [as 别名]
# 或者: from tkinter.Button import configure [as 别名]
class AddManually(Frame):
def __init__(self, parent, controller):
Frame.__init__(self, parent)
self.controller = controller
self.place(relx=0.0, rely=0.0, relheight=0.62, relwidth=0.72)
self.configure(relief=GROOVE)
self.configure(borderwidth="2")
self.configure(relief=GROOVE)
self.configure(width=125)
self.label_top = Label(self)
self.label_top.place(relx=0.4, rely=0.03, height=21, width=112)
self.label_top.configure(text="Add items manually")
self.name = Entry(self, fg='grey')
self.name.place(relx=0.05, rely=0.31, relheight=0.08, relwidth=0.29)
self.name.insert(0, "Input name here")
self.name.bind('<Button-1>', lambda event: greytext(self.name))
self.link = Entry(self, fg='grey')
self.link.place(relx=0.65, rely=0.31, relheight=0.08, relwidth=0.29)
self.link.insert(0, "Input link here")
self.link.bind('<Button-1>', lambda event: greytext(self.link))
self.add_btn = Button(self, command=self.send_data)
self.add_btn.place(relx=0.42, rely=0.44, height=34, width=100)
self.add_btn.configure(text="Add item")
self.back = Button(self, command=lambda: controller.show_frame('Main'))
self.back.place(relx=0.42, rely=0.64, height=34, width=100)
self.back.configure(text="Go back")
name_label = Label(self)
name_label.place(relx=0.05, rely=0.22, height=21, width=38)
name_label.configure(text="Name")
link_label = Label(self)
link_label.place(relx=0.65, rely=0.22, height=21, width=28)
link_label.configure(text="Link")
def send_data(self):
if self.link.cget('fg') == 'grey' or self.name.cget('fg') == 'grey':
return
link = self.link.get()
if link.strip() != '':
name = self.name.get()
self.controller.add_item(link, name)
print("Item added")
示例3: show
# 需要导入模块: from tkinter import Button [as 别名]
# 或者: from tkinter.Button import configure [as 别名]
def show(self):
self.__menu = Frame(self.__window)
self.__menu.configure(padx=10, pady=20)
self.__menu.pack(fill=BOTH, expand=True)
line1 = Frame(self.__menu)
line1.pack(fill=X)
self.__name = StringVar()
self.__name.set("my_game_at_"+strftime("%H:%M")+"-"+strftime("%d.%m.%Y"))
name_input = Entry(line1)
name_input.configure(textvariable=self.__name)
name_input.pack(fill=X)
line2 = Frame(self.__menu)
line2.pack(fill=X, pady=20)
save_btn = Button(line2)
save_btn.configure(text="Save Game", command=self.save)
save_btn.pack(fill=X)
示例4: _build_canvas
# 需要导入模块: from tkinter import Button [as 别名]
# 或者: from tkinter.Button import configure [as 别名]
def _build_canvas(self):
canvas = tk.Canvas(self, bg='white',
height=HEIGHT * UNIT,
width=WIDTH * UNIT)
# buttons
iteration_button = Button(self, text="Evaluate",
command=self.evaluate_policy)
iteration_button.configure(width=10, activebackground="#33B5E5")
canvas.create_window(WIDTH * UNIT * 0.13, HEIGHT * UNIT + 10,
window=iteration_button)
policy_button = Button(self, text="Improve",
command=self.improve_policy)
policy_button.configure(width=10, activebackground="#33B5E5")
canvas.create_window(WIDTH * UNIT * 0.37, HEIGHT * UNIT + 10,
window=policy_button)
policy_button = Button(self, text="move", command=self.move_by_policy)
policy_button.configure(width=10, activebackground="#33B5E5")
canvas.create_window(WIDTH * UNIT * 0.62, HEIGHT * UNIT + 10,
window=policy_button)
policy_button = Button(self, text="reset", command=self.reset)
policy_button.configure(width=10, activebackground="#33B5E5")
canvas.create_window(WIDTH * UNIT * 0.87, HEIGHT * UNIT + 10,
window=policy_button)
# create grids
for col in range(0, WIDTH * UNIT, UNIT): # 0~400 by 80
x0, y0, x1, y1 = col, 0, col, HEIGHT * UNIT
canvas.create_line(x0, y0, x1, y1)
for row in range(0, HEIGHT * UNIT, UNIT): # 0~400 by 80
x0, y0, x1, y1 = 0, row, HEIGHT * UNIT, row
canvas.create_line(x0, y0, x1, y1)
# add img to canvas
self.rectangle = canvas.create_image(50, 50, image=self.shapes[0])
canvas.create_image(250, 150, image=self.shapes[1])
canvas.create_image(150, 250, image=self.shapes[1])
canvas.create_image(250, 250, image=self.shapes[2])
# pack all
canvas.pack()
return canvas
示例5: App
# 需要导入模块: from tkinter import Button [as 别名]
# 或者: from tkinter.Button import configure [as 别名]
class App(object):
def __init__(self):
#настройка окружения
self.pathtoapp = path2program.abspath(".")
self.lst = [x for x in listdir(".") if ".prg" in x] #получаем список файлов с расширением prg
if len(self.lst)==0:
print("No prg file found in directory")
input()
_exit(0)
self.currentfileindex = 0 #устанавливаем индекс текущего файла
#настройка графики
self.window = Tk()
self.window.title("PRG Viewer by Novicov: "+self.pathtoapp)
w = 850
h = 500
self.window.minsize(width=w-100,height=h-100)
self.window.maxsize(width=w,height=h)
#иконка
_lst = sys_argv[0].split('\\')
self.window.iconbitmap('\\'.join(_lst[:-1])+'\\PRGViewer-logo.ico')
#ПАНЕЛИ
# self.leftframe = Frame(self.window, bg="blue", width=int(w*0.667),height=h)
self.leftframe = Frame(self.window, bg="grey", width=int(w*0.667),height=h)
# self.bottomleftframe = Frame(self.leftframe, bg="red", width=w//4, height=int(h*0.2))
self.bottomleftframe = Frame(self.leftframe, bg="grey", width=w//4, height=int(h*0.2))
# self.rightframe = Frame(self.window, bg="yellow",width=int(w*0.333),height=h)
self.rightframe = Frame(self.window, bg="dark grey",width=int(w*0.333),height=h)
#canvas
self.set_canvas( self.leftframe, bg="dark green", width=int(w*0.667),height=int(h*0.8))
# self.set_canvas( self.leftframe, bg="light green", width=100,height=100)
#кнопки
self.nextButton = Button(self.bottomleftframe,text="Next",width=10)
self.prevButton = Button(self.bottomleftframe,text="Prev",width=10)
#Список фильтров
self.Filter = PRGListBox(self.rightframe,width=w-500)
#Выбор файла платы
self.infoText = StringVar()
self.infoText.set("Current file: "+self.lst[self.currentfileindex])
self.info = Label(self.rightframe,text=self.infoText.get())
self.listFilesText = StringVar()
self.listFilesText.set("\n".join(["Files: "]+self.lst))
self.listfiles = Label(self.rightframe,text=self.listFilesText.get(),anchor="w",justify=LEFT)
self.helpText = Label(self.rightframe, text="Use Next/Prev (Pg Down/Up) buttons for change file\n"+
"Use Up,Down,Right,Left buttons for move field\n"+
"Select row in ListBox for change vision mode\n"+
"Use +/- (p/m) buttons for scaling of field",anchor="n",justify=LEFT)
def set_path_and_current(self, filename):
'''
эта функция обрабатывает полный путь до файла
'''
try:
_lst = filename.split('\\')
self.path = '\\'.join(_lst[:-2])
chdir('\\'.join(_lst[:-1]))
print(listdir("."))
self.lst = [x for x in listdir(".") if ".prg" in x]
self.currentfileindex = self.lst.index(_lst[-1])
self.infoText.set("Current file: "+self.lst[self.currentfileindex])
self.info.configure(text=self.infoText.get())
self.listFilesText.set("\n".join(self.lst))
self.listfiles.configure(text=self.listFilesText.get())
self.canvas.configure(self.lst[self.currentfileindex])
self.canvas.setdefault(reper=True)
#рисуем
self.canvas.paint()
#здесь мы создаем группу
gr = list()
for item in self.canvas.field:
print(item[2][2])
if not (item[2][2] in gr):#выделяем уникальные данные
gr.append(item[2][2])
self.Filter.lst.delete(2,END)
for item in gr:
self.Filter.lst.insert(END,item)
except IOError:
self.infoText.set("Error")
self.info.configure(text=self.infoText.get())
def set_canvas(self,master=None,height=500,width=500,bg="grey" ):
if master==None:
master=self.window
self.canvas = prgCanvas(master,height=height,width=width,bg=bg)
def nextprev(self,direction):
self.currentfileindex+=1 if abs(direction)==direction else -1
#.........这里部分代码省略.........
示例6: Tabblet
# 需要导入模块: from tkinter import Button [as 别名]
# 或者: from tkinter.Button import configure [as 别名]
class Tabblet():
def __init__(self):
self.tkvar = tkinter.Tk()
with open("options.json") as j:
joptions = json.load(j)
self.tkvar.wm_title("Tabblet")
self.tkvar.iconbitmap('resources\\tabbleto.ico')
self.screenwidth = self.tkvar.winfo_screenwidth()
self.screenheight = self.tkvar.winfo_screenheight()
self.windowwidth = int(joptions['width'])
self.windowheight = int(joptions['height'])
self.windowx = (self.screenwidth-self.windowwidth) / 2
self.windowy = ((self.screenheight-self.windowheight) / 2) - 27
self.geometrystring = '%dx%d+%d+%d' % (self.windowwidth, self.windowheight, self.windowx, self.windowy)
self.tkvar.geometry(self.geometrystring)
self.image_resetwindow = PhotoImage(file="resources\\resetwindow.gif")
self.button_resetwindow = Button(self.tkvar, command= lambda: self.tkvar.geometry(self.geometrystring))
self.button_resetwindow.configure(relief="flat", image=self.image_resetwindow)
self.button_resetwindow.pack(expand=False,anchor="ne")
self.tkvar.bind('<Configure>', lambda event: self.button_resetwindow.place(x=self.tkvar.winfo_width()-20, y=0))
self.tkvar.bind('<B1-Motion>', self.dragmotion)
self.tkvar.bind('<ButtonPress-1>', lambda event: self.mousestate(True))
self.tkvar.bind('<ButtonRelease-1>', lambda event: self.mousestate(False))
self.velocityx = 0
self.velocityy = 0
self.mousepositionsx = [2]
self.mousepositionsy = [2]
self.ismousepressed = False
self.labelvelocityind = Label(self.tkvar, text='•')
velocitythread = threading.Thread(target=self.velocitymanager)
velocitythread.daemon = True
velocitythread.start()
self.tkvar.mainloop()
def dragmotion(self, event):
#print(event.x, event.y)
self.mousepositionsx.append(event.x)
self.mousepositionsy.append(event.y)
self.mousepositionsx = self.mousepositionsx[-20:]
self.mousepositionsy = self.mousepositionsy[-20:]
print(event.x, event.y)
def mousestate(self, state):
self.ismousepressed = state
def velocitymanager(self):
while True:
if not self.ismousepressed:
try:
self.velocityx = (sum(self.mousepositionsx)/len(self.mousepositionsx)) - self.mousepositionsx[-1]
self.velocityy = (sum(self.mousepositionsy)/len(self.mousepositionsy)) - self.mousepositionsy[-1]
except:
self.velocityx = 0
self.velocityy = 0
self.velocityx = int(self.velocityx * 0.9)
self.velocityy = int(self.velocityy * 0.9)
#print(self.velocityx, self.velocityy, self.ismousepressed)
if abs(self.velocityx) < 2:
self.velocityx = 0
if abs(self.velocityy) < 2:
self.velocityy = 0
time.sleep(0.0165)
#60 fps baby
self.labelvelocityind.configure(text="•")
self.labelvelocityind.place(x=512+self.velocityx, y=288+self.velocityy)
self.mousepositionsx = self.mousepositionsx[1:]
self.mousepositionsy = self.mousepositionsy[1:]
示例7: update_value
# 需要导入模块: from tkinter import Button [as 别名]
# 或者: from tkinter.Button import configure [as 别名]
position_track.set(temp - 1)
update_value(temp - 1)
label_first_name = Label(window, text = 'First Name:', justify = 'right', padx = 5)
entry_first_name = Entry(window, textvariable = first_name)
label_last_name = Label(window, text = 'Last Name:', justify = 'right', padx = 5)
entry_last_name = Entry(window, textvariable = last_name)
label_email = Label(window, text = 'Email Address:', justify = 'right', padx = 5)
entry_email = Entry(window, textvariable = email)
button_first = Button(window, text = 'First', command = first_value)
button_last = Button(window, text = 'Last', command = last_value)
button_prev = Button(window, text = 'Prev', command = prev_value)
button_next = Button(window, text = 'Next', command = next_value)
button_quit = Button(window, text = 'Quit')
button_quit.configure(command=window.destroy)
labels = [label_first_name, label_last_name, label_email]
entries = [entry_first_name, entry_last_name, entry_email]
buttons = [button_first, button_last, button_prev, button_next, button_last, button_quit]
for i in range(3):
labels[i].grid(row = i, column = 0, sticky = 'W')
entries[i].grid(row = i, column = 1, columnspan = 6)
for j in range(6):
buttons[j].grid(row = 3, column = j, sticky = 'E')
window.mainloop()
示例8: ReadFromFile
# 需要导入模块: from tkinter import Button [as 别名]
# 或者: from tkinter.Button import configure [as 别名]
class ReadFromFile(Frame):
def __init__(self, parent, controller):
Frame.__init__(self, parent)
self.controller = controller
self.link_first = True
self.items = []
self.place(relx=0.0, rely=0.0, relheight=0.62, relwidth=0.72)
self.configure(relief=GROOVE)
self.configure(borderwidth="2")
label_top = Label(self)
label_top.place(relx=0.42, rely=0.03, height=21, width=105)
label_top.configure(text="Select a file to read")
self.file_select = Button(self, command=self.fopen)
self.file_select.place(relx=0.43, rely=0.14, height=34, width=97)
self.file_select.configure(text="Select file")
self.back = Button(self, command=lambda: controller.show_frame('Main'))
self.back.place(relx=0.8, rely=0.87, height=34, width=97)
self.back.configure(text="Go back")
self.delimeter = Entry(self)
self.delimeter.place(relx=0.02, rely=0.11, relheight=0.06, relwidth=0.21)
self.delimeter.insert(0, ' -<>- ')
label_delim = Label(self)
label_delim.place(relx=0.02, rely=0.03, height=21, width=57)
label_delim.configure(text="Delimeter")
self.switch_label = Label(self)
self.switch_label.place(relx=0.73, rely=0.31, height=21, width=38)
self.switch_label.configure(text="Link")
self.switch_label2 = Label(self)
self.switch_label2.place(relx=0.9, rely=0.31, height=21, width=38)
self.switch_label2.configure(text="Name")
self.change_order = Button(self, command=self.switch_order)
self.change_order.place(relx=0.82, rely=0.31, height=24, width=32)
self.change_order.configure(text="<->")
name_or_link = Label(self)
name_or_link.place(relx=0.75, rely=0.19, height=21, width=97)
name_or_link.configure(text="Name or link first")
self.items_text = Text(self)
self.items_text.place(relx=0.02, rely=0.5, relheight=0.46, relwidth=0.76)
self.items_text.configure(wrap=tk.WORD)
label_items = Label(self)
label_items.place(relx=0.35, rely=0.42, height=21, width=35)
label_items.configure(text="Items")
self.commit_btn = Button(self, command=self.commit)
self.commit_btn.place(relx=0.83, rely=0.64, height=34, width=67)
self.commit_btn.configure(text="Commit")
self.Label12 = Label(self)
self.Label12.place(relx=0.02, rely=0.19, height=21, width=88)
self.Label12.configure(text="Link formatting (optional)")
self.link_part1 = Entry(self, fg='grey')
self.link_part1.place(relx=0.02, rely=0.28, relheight=0.06, relwidth=0.37)
self.link_part1.insert(0, "Start of the link here")
self.link_part1.bind('<Button-1>', lambda event: greytext(self.link_part1))
self.link_part2 = Entry(self, fg='grey')
self.link_part2.place(relx=0.02, rely=0.36, relheight=0.06, relwidth=0.37)
self.link_part2.insert(0, "End of the link here")
self.link_part2.bind('<Button-1>', lambda event: greytext(self.link_part2))
def fopen(self):
filename = askopenfilename()
if filename == '':
return
self.items.clear()
self.items_text.delete(1.0, 'end')
with open(filename, encoding='utf-8-sig') as f:
lines = f.read().splitlines()
delim = self.delimeter.get()
for line in lines:
try:
link, name = line.split(delim, 1)
if not self.link_first:
name, link = link, name
if '{DELETED} ' in name[:13]:
continue
s, e = self.get_link_formatting()
link = s + link + e
self.items += [(link, name)]
self.items_text.insert('end', ("name: " + name + "\nlink: " +
link + '\n\n'))
except ValueError:
print("Something went wrong: ", line)
def get_link_formatting(self):
#.........这里部分代码省略.........
示例9: Main
# 需要导入模块: from tkinter import Button [as 别名]
# 或者: from tkinter.Button import configure [as 别名]
class Main(Frame):
def __init__(self, parent, controller):
Frame.__init__(self, parent)
self.controller = controller
self.db_set = False
self.configure(relief=GROOVE)
self.configure(borderwidth="2")
# Manual link adding
self.manual_btn = Button(self)
self.manual_btn.place(relx=0.07, rely=0.81, height=45, width=130)
self.manual_btn.configure(activebackground="#d9d9d9")
self.manual_btn.configure(highlightbackground="#d9d9d9")
self.manual_btn.configure(pady="0")
self.manual_btn.configure(text="Add manually")
self.manual_btn.configure(width=130)
self.file_btn = Button(self)
self.file_btn.place(relx=0.67, rely=0.81, height=45, width=150)
self.file_btn.configure(activebackground="#d9d9d9")
self.file_btn.configure(highlightbackground="#d9d9d9")
self.file_btn.configure(pady="0")
self.file_btn.configure(text="Add from file")
self.label = Label(self)
self.label.place(relx=0.08, rely=0.0, height=61, width=484)
self.label.configure(text="Create new playlists and add content to them")
self.label.configure(width=485)
self.listbox = Listbox(self)
self.listbox.place(relx=0.38, rely=0.22, relheight=0.31, relwidth=0.17)
self.listbox.configure(background="white")
self.listbox.configure(disabledforeground="#a3a3a3")
self.listbox.configure(foreground="#000000")
self.listbox.configure(selectmode=SINGLE)
self.listbox.configure(width=105)
for name, value in config.configparser.items('Playlists'):
if os.path.isdir(value):
self.listbox.insert('end', name)
else:
config.remove_value('Playlists', name)
self.listbox.bind('<<ListboxSelect>>', self.onselect)
self.label_name = Label(self)
self.label_name.place(relx=0.7, rely=0.22, height=31, width=84)
self.label_name.configure(foreground="#000000")
self.label_name.configure(text="Name")
self.label_name.configure(width=85)
self.entry = Entry(self)
self.entry.place(relx=0.63, rely=0.31, relheight=0.08, relwidth=0.29)
self.entry.configure(background="white")
self.entry.configure(foreground="#000000")
self.entry.configure(insertbackground="black")
self.entry.configure(takefocus="0")
self.entry.configure(width=175)
self.change_name = Button(self)
self.change_name.place(relx=0.7, rely=0.42, height=34, width=97)
self.change_name.configure(activebackground="#d9d9d9")
self.change_name.configure(highlightbackground="#d9d9d9")
self.change_name.configure(highlightcolor="black")
self.change_name.configure(pady="0")
self.change_name.configure(text="Rename")
self.change_name.configure(width=100)
self.new_playlist = Button(self, command=self.new_database)
self.new_playlist.place(relx=0.08, rely=0.28, height=54, width=107)
self.new_playlist.configure(activebackground="#d9d9d9")
self.new_playlist.configure(highlightbackground="#d9d9d9")
self.new_playlist.configure(highlightcolor="black")
self.new_playlist.configure(pady="0")
self.new_playlist.configure(text="Create new playlist")
self.new_playlist.configure(width=105)
self.db_name = Entry(self)
self.db_name.place(relx=0.07, rely=0.44, relheight=0.08, relwidth=0.22)
self.db_name.configure(fg='grey')
self.db_name.configure(width=135)
self.db_name.insert(0, "Input database name here")
self.db_name.bind('<Button-1>', lambda event: greytext(self.db_name))
def onselect(self, event):
w = event.widget
index = int(w.curselection()[0])
value = w.get(index)
set_database(config.configparser.get('Playlists', value))
if not database.check_integrity():
messagebox.showwarning('Integrity check failed', 'You might be missing some entries in your list')
if not self.db_set:
self.manual_btn.configure(command=lambda: self.controller.show_frame('AddManually'))
self.file_btn.configure(command=lambda: self.controller.show_frame('ReadFromFile'))
self.db_set = True
def new_database(self):
name = self.db_name.get()
names = config.configparser.options('Playlists')
print(name, names)
if name.strip() == '' or self.db_name.cget('fg') == 'grey':
#.........这里部分代码省略.........
示例10: Placer
# 需要导入模块: from tkinter import Button [as 别名]
# 或者: from tkinter.Button import configure [as 别名]
#.........这里部分代码省略.........
'Zero Node Path',
label = 'Zero All',
command = self.zeroAll)
self.menuBar.addmenuitem('Placer', 'command',
'Reset Node Path',
label = 'Reset All',
command = self.resetAll)
self.menuBar.addmenuitem('Placer', 'command',
'Print Node Path Info',
label = 'Print Info',
command = self.printNodePathInfo)
self.menuBar.addmenuitem(
'Placer', 'command',
'Toggle widget visability',
label = 'Toggle Widget Vis',
command = SEditor.toggleWidgetVis)
self.menuBar.addmenuitem(
'Placer', 'command',
'Toggle widget manipulation mode',
label = 'Toggle Widget Mode',
command = SEditor.manipulationControl.toggleObjectHandlesMode)
# Get a handle to the menu frame
menuFrame = self.menuFrame
self.nodePathMenu = Pmw.ComboBox(
menuFrame, labelpos = tkinter.W, label_text = 'Node Path:',
entry_width = 20,
selectioncommand = self.selectNodePathNamed,
scrolledlist_items = self.nodePathNames)
self.nodePathMenu.selectitem('selected')
self.nodePathMenuEntry = (
self.nodePathMenu.component('entryfield_entry'))
self.nodePathMenuBG = (
self.nodePathMenuEntry.configure('background')[3])
self.nodePathMenu.pack(side = 'left', fill = 'x', expand = 1)
self.bind(self.nodePathMenu, 'Select node path to manipulate')
modeMenu = Pmw.OptionMenu(menuFrame,
items = ('Relative To:',
'Orbit:'),
initialitem = 'Relative To:',
command = self.setMovementMode,
menubutton_width = 8)
modeMenu.pack(side = 'left', expand = 0)
self.bind(modeMenu, 'Select manipulation mode')
self.refNodePathMenu = Pmw.ComboBox(
menuFrame, entry_width = 16,
selectioncommand = self.selectRefNodePathNamed,
scrolledlist_items = self.refNodePathNames)
self.refNodePathMenu.selectitem('parent')
self.refNodePathMenuEntry = (
self.refNodePathMenu.component('entryfield_entry'))
self.refNodePathMenu.pack(side = 'left', fill = 'x', expand = 1)
self.bind(self.refNodePathMenu, 'Select relative node path')
self.undoButton = Button(menuFrame, text = 'Undo',
command = SEditor.undo)
if SEditor.undoList:
self.undoButton['state'] = 'normal'
else:
self.undoButton['state'] = 'disabled'
self.undoButton.pack(side = 'left', expand = 0)
self.bind(self.undoButton, 'Undo last operation')
self.redoButton = Button(menuFrame, text = 'Redo',
示例11: MainWin
# 需要导入模块: from tkinter import Button [as 别名]
# 或者: from tkinter.Button import configure [as 别名]
class MainWin(Tk):
def __init__(self, client):
Tk.__init__(self)
self.client = client
self.programPanel = ProgramPanel(client)
self.programPanel.grid(row = 0, column = 0, sticky = NSEW)
self.frame = Frame(self)
self.frame.grid(row = 0, column = 0, sticky = NSEW)
nextRow = Counter()
# Create the menu.
menu = Frame(self.frame)
addButton = Menubutton(menu, text = 'Add')
addButton.pack()
menu.grid(row = nextRow(), column = 0, sticky = W)
# Create the program panel.
self.program = ProgramWidget(self.frame, client)
self.program.grid(row = nextRow(), column = 0, columnspan = 2,
sticky = W)
label = Label(self.frame, text = 'AWB')
label.grid(row = nextRow(), column = 0)
self.recordMode = Button(self.frame, text = 'P',
command = self.toggleRecord)
modeRow = nextRow()
self.recordMode.grid(row = modeRow, column = 0, sticky = W)
self.status = Label(self.frame, text = 'Idle')
self.status.grid(row = modeRow, column = 1)
self.channels = []
self.channelFrame = Frame(self.frame)
self.channelFrame.grid(row = nextRow(), columnspan = 2)
self.bind('q', self.terminate)
self.bind('f', self.foo)
self.bind('r', self.toggleRecord)
self.bind('k', self.toggleSticky)
self.bind('.', self.nextSection)
self.bind(',', self.prevSection)
self.bind('<space>', self.togglePause)
self.bind('K', self.clearAllState)
self.protocol('WM_DELETE_WINDOW', self.destroy)
self.bind('<F1>', lambda evt: self.frame.tkraise())
self.bind('<F2>', lambda evt: self.programPanel.tkraise())
for i in range(0, 8):
# Bind number key.
self.bind(str(i),
lambda evt, channel = i: self.toggleChannel(channel)
)
# Create channel
channel = Channel(self.channelFrame, i)
self.channels.append(channel)
channel.pack(side = LEFT)
client.addChannelSubscriber(
i,
lambda ch, status, channel = channel:
channel.changeStatus(status)
)
def foo(self, event):
print('got foo')
def terminate(self, event):
self.destroy()
def toggleRecord(self, event):
self.client.recordEnabled = not self.client.recordEnabled
self.recordMode.configure(text = self.client.recordEnabled and 'R' or
'P'
)
def togglePause(self, event):
self.client.togglePause()
if self.client.paused:
self.status.configure(text = 'Paused')
else:
self.status.configure(text = 'Playing')
def clearAllState(self, event):
self.client.clearAllState()
self.status.configure(text = 'Idle')
for channel in self.channels:
channel.changeStatus(0)
def toggleChannel(self, channel):
# using "channel" as program
self.client.activate(channel)
if self.client.recording.get(channel):
self.client.endRecord(channel)
elif self.client.recordEnabled:
#.........这里部分代码省略.........
示例12: TimerFrame
# 需要导入模块: from tkinter import Button [as 别名]
# 或者: from tkinter.Button import configure [as 别名]
class TimerFrame(Frame):
# tkinter widgets
timer_control_btn = current_time_lbl = copyright_lbl = remaining_time_frame = None
section_title_lbl = elapsed_time_lbl = remaining_time_lbl = reset_timer_btn = None
inverting_parts = []
ui_colors = [LIGHT, DARK]
# timer logic
_actual_section = 0
section_remaining = EXAM_SECTIONS[_actual_section][1]
timer_id = None
def __init__(self, master=None, cnf={}, **kw):
super().__init__(master, cnf, **kw)
self.COPYRIGHT_FONT = Font(master, family='Helvetica', size=28)
self.LABELS_FONT = Font(master, family='Helvetica', size=50)
self.SECTION_FONT = Font(master, family='Helvetica', size=76)
self.TIME_FONT = Font(master, family='Helvetica', size=130, weight=BOLD)
self.setup_ui()
self.bind_keyboard()
self._update_current_time()
def setup_ui(self):
"""
Basic setup GUI labels and buttons.
"""
self.pack(fill=BOTH, expand=True, padx=10, pady=10)
self.grid_columnconfigure(1, weight=1)
self.grid_rowconfigure(1, weight=1)
self.timer_control_btn = Button(self, command=self.start_timer, text='START!', font=self.LABELS_FONT)
self.timer_control_btn.grid(row=2, column=1, sticky=S)
self.reset_timer_btn = Button(
self, command=self.reset_timer,
text='VYNULOVAT!', font=self.COPYRIGHT_FONT
)
self.reset_timer_btn.grid(row=2, column=2, sticky=S + E)
self.current_time_lbl = Label(self, font=self.LABELS_FONT)
self.current_time_lbl.grid(row=2, column=0, sticky=W + S)
self.copyright_lbl = Label(self, text="Josef Kolář © 2016", font=self.COPYRIGHT_FONT)
self.copyright_lbl.grid(column=2, row=0, sticky=N + E)
self.section_title_lbl = Label(self, font=self.SECTION_FONT)
self.section_title_lbl.grid(column=1, row=0, sticky=N)
self.elapsed_time_lbl = Label(self, text='0:00', font=self.LABELS_FONT)
self.elapsed_time_lbl.grid(column=0, row=0, sticky=N + W)
self.remaining_time_frame = Frame(self)
self.remaining_time_frame.grid(column=1, row=1)
self.remaining_time_lbl = Label(
self.remaining_time_frame,
text=format_delta(EXAM_SECTIONS[0][1]), font=self.TIME_FONT
)
self.remaining_time_lbl.pack()
self.inverting_parts.extend((
self.current_time_lbl,
self.copyright_lbl,
self.section_title_lbl,
self.remaining_time_lbl,
self.timer_control_btn,
self.elapsed_time_lbl,
self.reset_timer_btn
))
self.refresh_section()
def _update_current_time(self):
"""
Update the timer of current time and set the timing for next second.
"""
self.current_time_lbl.configure(text=time.strftime('%H:%M:%S'))
self.master.after(1000, self._update_current_time)
def _invert_ui(self):
"""
Invert colors in the GUI including font colors and backgrounds.
"""
self.ui_colors.reverse()
bg, fg = self.ui_colors
self.master.configure(bg=bg)
self.configure(bg=bg)
for part in self.inverting_parts:
part['background'] = bg
part['foreground'] = fg
def start_timer(self):
"""
Start the main timer and timer updating.
"""
self.timer_control_btn.configure(text='STOP!', command=self.stop_timer)
self.timer_id = self.master.after(1000, self.update_timer)
#.........这里部分代码省略.........
示例13: __init__
# 需要导入模块: from tkinter import Button [as 别名]
# 或者: from tkinter.Button import configure [as 别名]
#.........这里部分代码省略.........
self.working_output_label.place(height=25, width=200, x=10, y=100)
self.log_frame.place(height=135, width=400, x=240, y=270)
self.log_text.place(height=115, width=380, x=10, y=10)
self.plot_frame.place(x=640, y=10, width=360, height=395)
self.switch_plot_left_button.place(x=5, y=5, height=30, width=30)
self.switch_plot_right_button.place(x=325, y=5, height=30, width=30)
self.plot_label.place(x=35, y=5, height=25, width=295)
self.pyrometer_plot_frame.place(x=5, y=40, width=350, height=350)
self.oven_temperature_plot_frame.place(x=5, y=40, width=350, height=350)
self.power_ouput_plot_frame.place(x=5, y=40, width=350, height=350)
self.pyrometer_plot.place(x=0, y=0, width=350, height=350)
self.oven_temperature_plot.place(x=0, y=00, width=350, height=350)
self.power_ouput_plot.place(x=0, y=0, width=350, height=350)
self.oven_temperature_plot_frame.lift()
def start_label_updater(self):
"""Read values from instrument objects every second, display them, plot them and write in a logfile"""
self.start_time = datetime.now()
def update_labels():
while True:
pyrometer_temperature = "---"
oven_temperature = "---"
working_output = "---"
working_setpoint = "---"
runtime = (datetime.now() - self.start_time).seconds / 60.0
if self.PLD is not None:
oven_temperature = self.PLD.oven_temp.get()
self.oven_temperature_plot.add_datapoint(runtime, oven_temperature)
self.oven_temperature_label.configure(text="Oven temperature: %s °C" % oven_temperature)
working_output = self.PLD.working_output.get()
self.power_ouput_plot.add_datapoint(runtime, working_output)
self.working_output_label.configure(text="Working output: %s %%" % working_output)
working_setpoint = self.PLD.working_setpoint.get()
self.working_setpoint_label.configure(text="Working setpoint: %s °C" % working_setpoint)
if self.pyrometer is not None:
pyrometer_temperature = self.pyrometer.temperature.get()
self.pyrometer_plot.add_datapoint(runtime, pyrometer_temperature)
self.external_temperature_label.configure(text="Sample temperature %s °C" % pyrometer_temperature)
logstring = "Time: " + strftime("%X") \
+ ("Oven temperature: %s °C" % oven_temperature).ljust(28, " ") \
+ ("Power Output %s %%" % working_output).ljust(28, " ")\
+ ("Working Setpoint: %s °C" % working_setpoint).ljust(28, " ")\
+ ("Pyrometer temperature: %s °C" % pyrometer_temperature).ljust(28, " ") \
+ "\n"
printstring = "Time: " + strftime("%X") \
+ ("Oven temperature: %s °C" % oven_temperature).ljust(28, " ") \
+ ("Pyrometer temperature: %s °C" % pyrometer_temperature).ljust(28, " ")\
+ "\n"
self.log_text.insert(END, printstring)
sleep(0.5)
self.label_updater._target = update_labels
self.label_updater.start()
if self.PLD is not None and self.pyrometer is not None:
self.start_pyrometer_pld_communication()
示例14: __init__
# 需要导入模块: from tkinter import Button [as 别名]
# 或者: from tkinter.Button import configure [as 别名]
class GuessingGame:
def __init__(self, master):
self.master = master
master.title("Guessing Game")
self.secret_number = random.randint(1, 100)
self.guess = None
self.num_guesses = 0
self.message = "Guess a number from 1 to 100"
self.label_text = StringVar()
self.label_text.set(self.message)
self.label = Label(master, textvariable=self.label_text)
vcmd = master.register(self.validate) # we have to wrap the command
self.entry = Entry(master, validate="key", validatecommand=(vcmd, '%P'))
self.guess_button = Button(master, text="Guess", command=self.guess_number)
self.reset_button = Button(master, text="Play again", command=self.reset, state=DISABLED)
self.label.grid(row=0, column=0, columnspan=2, sticky=W+E)
self.entry.grid(row=1, column=0, columnspan=2, sticky=W+E)
self.guess_button.grid(row=2, column=0)
self.reset_button.grid(row=2, column=1)
def validate(self, new_text):
if not new_text: # the field is being cleared
self.guess = None
return True
try:
guess = int(new_text)
if 1 <= guess <= 100:
self.guess = guess
return True
else:
return False
except ValueError:
return False
def guess_number(self):
self.num_guesses += 1
if self.guess is None:
self.message = "Guess a number from 1 to 100"
elif self.guess == self.secret_number:
suffix = '' if self.num_guesses == 1 else 'es'
self.message = "Congratulations! You guessed the number after %d guess%s." % (self.num_guesses, suffix)
self.guess_button.configure(state=DISABLED)
self.reset_button.configure(state=NORMAL)
elif self.guess < self.secret_number:
self.message = "Too low! Guess again!"
else:
self.message = "Too high! Guess again!"
self.label_text.set(self.message)
def reset(self):
self.entry.delete(0, END)
self.secret_number = random.randint(1, 100)
self.guess = 0
self.num_guesses = 0
self.message = "Guess a number from 1 to 100"
self.label_text.set(self.message)
self.guess_button.configure(state=NORMAL)
self.reset_button.configure(state=DISABLED)
示例15: FilePickEdit
# 需要导入模块: from tkinter import Button [as 别名]
# 或者: from tkinter.Button import configure [as 别名]
class FilePickEdit(Frame):
def __init__(self, master, file_mask, default_file, edit_height = None, user_onChange = None,
rename_on_edit=0, font = None, coloring=True, allowNone=False, highlighter=None, directory='.'):
"""
file_mask: file mask (e.g. "*.foo") or list of file masks (e.g. ["*.foo", "*.abl"])
"""
self.master = master
self.directory = directory
self.user_onChange = user_onChange
Frame.__init__(self, master)
row = 0
self.unmodified = True
self.allowNone = allowNone
self.file_extension = ""
if type(file_mask) != list:
file_mask = [file_mask]
if "." in file_mask[0]:
self.file_extension = file_mask[0][file_mask[0].rfind('.'):]
# read filenames
self.file_mask = file_mask
self.updateList()
# filename frame
self.list_frame = Frame(self)
self.list_frame.grid(row=row, column=0, sticky="WE")
self.list_frame.columnconfigure(0, weight=1)
# create list
self.picked_name = StringVar()
self.makelist()
# refresh button
self.refresh_button = Button(self.list_frame, text='<- refresh', command=self.refresh, height=1)
self.refresh_button.grid(row=0, column=1, sticky='E')
# save button
self.save_button = Button(self.list_frame, text="save", command=self.save, height=1)
self.save_button.grid(row=0, column=2, sticky="E")
# editor
row += 1
if coloring:
self.editor = SyntaxHighlightingText(self, self.onEdit, highlighter=highlighter)
else:
self.editor = ScrolledText2(self, self.onEdit)
if font is not None:
self.editor.configure(font=font)
if edit_height is not None:
self.editor.configure(height=edit_height)
self.editor.grid(row=row, column=0, sticky="NEWS")
self.rowconfigure(row, weight=1)
self.columnconfigure(0, weight=1)
# option to change filename on edit
row += 1
self.options_frame = Frame(self)
self.options_frame.grid(row=row, column=0, sticky=W)
self.rename_on_edit = IntVar()
self.cb = Checkbutton(self.options_frame, text="rename on edit", variable=self.rename_on_edit)
self.cb.pack(side=LEFT)
self.cb.configure(command=self.onChangeRename)
self.rename_on_edit.set(rename_on_edit)
# filename frame
row += 1
self.filename_frame = Frame(self)
self.filename_frame.grid(row=row, column=0, sticky="WE")
self.filename_frame.columnconfigure(0, weight=1)
# save as filename
self.save_name = StringVar()
self.save_edit = Entry(self.filename_frame, textvariable = self.save_name)
self.save_edit.grid(row=0, column=0, sticky="WE")
self.save_name.trace("w", self.onSaveChange)
# pick default if applicableButton
self.select(default_file)
self.row = row
def setDirectory(self, directory, keep=False):
self.directory = directory
self.updateList()
self.makelist()
# menu = self.list["menu"] scrolledlist
# menu = self.list.listbox#["scrolledlist"]
# menu.delete(0, 'end')
# add the new ones
# for filename in self.files:
# menu.add_command(label=filename, command=_setit(self.picked_name, filename, None))
# if keep is true, only the files list will be updated but the content of the
# text area will not be altered/removed
if not keep: self.select("")
def refresh(self):
sel = self.get()
self.updateList()
self.select(sel, notify=False)
def reloadFile(self):
self.editor.delete("1.0", END)
filename = self.picked_name.get()
if os.path.exists(os.path.join(self.directory, filename)):
new_text = open(os.path.join(self.directory, filename)).read()
if new_text.strip() == "":
new_text = "// %s is empty\n" % filename
new_text = new_text.replace("\r", "")
else:
new_text = ""
#.........这里部分代码省略.........