本文整理汇总了Python中tkinter.ttk.Label.configure方法的典型用法代码示例。如果您正苦于以下问题:Python Label.configure方法的具体用法?Python Label.configure怎么用?Python Label.configure使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tkinter.ttk.Label
的用法示例。
在下文中一共展示了Label.configure方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: PredictionWidget
# 需要导入模块: from tkinter.ttk import Label [as 别名]
# 或者: from tkinter.ttk.Label import configure [as 别名]
class PredictionWidget(Frame):
"""Shows a prediction to the user."""
def __init__(self, master):
"""Make boxes, register callbacks etc."""
Frame.__init__(self, master)
self.active_category = StringVar()
self.bind("<Configure>", self.onResize)
self.date = None
self.predictor = Predictor()
self.category_buttons = self.createCategoryButtons()
self.text = Label(self, justify=CENTER, font="Arial 14")
def createCategoryButtons(self):
"""Create the buttons used to choose category. Return them."""
result = []
icons = self.readIcons()
categories = self.predictor.categories()
for i in categories:
if i in icons:
icon = icons[i]
else:
icon = icons["= default ="]
category_button = Radiobutton(self, image=icon,
variable=self.active_category, value=i, indicatoron=False,
width=icon_size, height=icon_size, command=self.update)
category_button.image_data = icon
result.append(category_button)
self.active_category.set(categories[0])
return result
def readIcons(self):
"""Read the gui icons from disk. Return them."""
result = {}
categories = open(nextToThisFile("icons.txt")).read().split("\n\n")
for i in categories:
category_name, file_data = i.split("\n", maxsplit=1)
image = PhotoImage(data=file_data)
result[category_name] = image
return result
def onResize(self, event):
"""Rearrange the children when the geometry of self changes."""
if event.widget == self:
center = (event.width / 2, event.height / 2)
radius = min(center) - icon_size / 2
self.text.place(anchor=CENTER, x=center[0], y=center[1])
for i, j in enumerate(self.category_buttons):
turn = 2 * math.pi
angle = turn * (1 / 4 - i / len(self.category_buttons))
j.place(anchor=CENTER,
x=center[0] + math.cos(angle) * radius,
y=center[1] - math.sin(angle) * radius)
def update(self, date=None):
"""Change contents based on circumstances. Set date if given."""
if date:
self.date = date
if self.date:
predictions = self.predictor.predict(self.date)
prediction = predictions[self.active_category.get()]
prediction = textwrap.fill(prediction, width=20)
else:
prediction = ""
self.text.configure(text=prediction)
示例2: average_normals
# 需要导入模块: from tkinter.ttk import Label [as 别名]
# 或者: from tkinter.ttk.Label import configure [as 别名]
def average_normals( self ):
""" Applies Gouraud normalization to the module
"""
# Set up updater
top = Toplevel()
pb = Progressbar(top,orient ="horizontal",length = 200, mode ="determinate")
pb['maximum'] = len(self.__elements__)
pb['value'] = 10
pb.grid(row=0,column=0)
tx = Label(top)
tx.grid(row=1,column=0)
top.update_idletasks()
top.lift()
t0 = time.time()
# run the loop, if we're visible and phong shading
if not self.invisible == 'gouroud':
try:
buf = np.array([0,0,0,1])
for i,polygon in enumerate(self.__elements__):
if not ispoly(polygon): continue
polygon._onorms = np.array([polygon.normals.astype(float)+buf for i in range(len(polygon.coordinates))])
# Update the user as to what's going on
if i % 50 == 0 and i > 0:
pb['value'] = i
tmp = i/len(self.__elements__)
estimation = int(tmp*(time.time()-t0) * (1-tmp)/tmp)
tx.configure(text=str(int(100*i/len(self.__elements__)))+"%"+' Estimated time: '+str(estimation)+'s' )
top.update_idletasks()
for c,coordinate in enumerate(polygon.coordinates):
for j,opolygon in enumerate(self.__elements__):
if i == j or not ispoly(opolygon): continue
for k,ocoordinate in enumerate(opolygon.coordinates):
if all(coordinate == ocoordinate): # same vertex, finally
polygon._onorms[c] += (opolygon.normals+buf)
polygon._onorms /= polygon._onorms[:,3,None]
for polygon in self.__elements__:
if ispoly(polygon):
polygon.normals = polygon._onorms
del polygon._onorms
except IndexError as ie: pass
top.destroy()
if self.invisible == 'gouroud':
self.invisible = False
return self # for chaining
示例3: MainWindow
# 需要导入模块: from tkinter.ttk import Label [as 别名]
# 或者: from tkinter.ttk.Label import configure [as 别名]
class MainWindow(object):
def __init__(self, root, options):
'''
-----------------------------------------------------
| main button toolbar |
-----------------------------------------------------
| < ma | in content area > |
| | |
| File list | File name |
| | |
-----------------------------------------------------
| status bar area |
-----------------------------------------------------
'''
# Obtain and expand the current working directory.
if options.path:
base_path = os.path.abspath(options.path)
else:
base_path = os.path.abspath(os.getcwd())
self.base_path = os.path.normcase(base_path)
# Create a filename normalizer based on the CWD.
self.filename_normalizer = filename_normalizer(self.base_path)
# Set up dummy coverage data
self.coverage_data = {'lines': {}, 'total_coverage': None}
# Root window
self.root = root
self.root.title('Duvet')
self.root.geometry('1024x768')
# Prevent the menus from having the empty tearoff entry
self.root.option_add('*tearOff', tk.FALSE)
# Catch the close button
self.root.protocol("WM_DELETE_WINDOW", self.cmd_quit)
# Catch the "quit" event.
self.root.createcommand('exit', self.cmd_quit)
# Setup the menu
self._setup_menubar()
# Set up the main content for the window.
self._setup_button_toolbar()
self._setup_main_content()
self._setup_status_bar()
# Now configure the weights for the root frame
self.root.columnconfigure(0, weight=1)
self.root.rowconfigure(0, weight=0)
self.root.rowconfigure(1, weight=1)
self.root.rowconfigure(2, weight=0)
######################################################
# Internal GUI layout methods.
######################################################
def _setup_menubar(self):
# Menubar
self.menubar = tk.Menu(self.root)
# self.menu_Apple = Menu(self.menubar, name='Apple')
# self.menubar.add_cascade(menu=self.menu_Apple)
self.menu_file = tk.Menu(self.menubar)
self.menubar.add_cascade(menu=self.menu_file, label='File')
self.menu_help = tk.Menu(self.menubar)
self.menubar.add_cascade(menu=self.menu_help, label='Help')
# self.menu_Apple.add_command(label='Test', command=self.cmd_dummy)
# self.menu_file.add_command(label='New', command=self.cmd_dummy, accelerator="Command-N")
# self.menu_file.add_command(label='Close', command=self.cmd_dummy)
self.menu_help.add_command(label='Open Documentation', command=self.cmd_duvet_docs)
self.menu_help.add_command(label='Open Duvet project page', command=self.cmd_duvet_page)
self.menu_help.add_command(label='Open Duvet on GitHub', command=self.cmd_duvet_github)
self.menu_help.add_command(label='Open BeeWare project page', command=self.cmd_beeware_page)
# last step - configure the menubar
self.root['menu'] = self.menubar
def _setup_button_toolbar(self):
'''
The button toolbar runs as a horizontal area at the top of the GUI.
It is a persistent GUI component
'''
# Main toolbar
self.toolbar = tk.Frame(self.root)
self.toolbar.grid(column=0, row=0, sticky=(tk.W, tk.E))
# Buttons on the toolbar
self.refresh_button = tk.Button(self.toolbar, text='Refresh', command=self.cmd_refresh)
self.refresh_button.grid(column=0, row=0)
# Coverage summary for currently selected file.
self.coverage_total_summary = tk.StringVar()
#.........这里部分代码省略.........
示例4: __init__
# 需要导入模块: from tkinter.ttk import Label [as 别名]
# 或者: from tkinter.ttk.Label import configure [as 别名]
class LoginFrame:
def __init__(self, url):
self.url = url
self.root = Tk()
self.root.title("验证码")
while True:
try:
image_bytes = urlopen(self.url).read()
break
except socket.timeout:
print('获取验证码超时:%s\r\n重新获取.' % (self.url))
continue
except urllib.error.URLError as e:
if isinstance(e.reason, socket.timeout):
print('获取验证码超时:%s\r\n重新获取.' % (self.url))
continue
# internal data file
data_stream = io.BytesIO(image_bytes)
# open as a PIL image object
self.pil_image = Image.open(data_stream)
# convert PIL image object to Tkinter PhotoImage object
self.tk_image = ImageTk.PhotoImage(self.pil_image)
self.label = Label(self.root, image=self.tk_image, background='brown')
self.label.pack(padx=5, pady=5)
self.button = Button(self.root, text="刷新验证码", command=self.refreshImg)
self.button.pack(padx=5, pady=5)
randCodeLable = Label(self.root, text="验证码:")
randCodeLable.pack(padx=5, pady=5)
self.randCode = Entry(self.root)
self.randCode.pack(padx=5, pady=5)
self.loginButton = Button(self.root, text="登录", default=tkinter.ACTIVE)
self.loginButton.pack(padx=5, pady=5)
def refreshImg(self):
url = self.url
while True:
try:
image_bytes = urlopen(url).read()
data_stream = io.BytesIO(image_bytes)
self.pil_image = Image.open(data_stream)
self.tk_image = ImageTk.PhotoImage(self.pil_image)
self.label.configure(image=self.tk_image)
break
except socket.timeout:
print('获取验证码超时:%s\r\n重新获取.' % (self.url))
continue
except urllib.error.URLError as e:
if isinstance(e.reason, socket.timeout):
print('获取验证码超时:%s\r\n重新获取.' % (self.url))
continue
# 显示URL地址指定图片
def show(self):
w, h = self.pil_image.size
# 窗体居中
width = w + 100
height = h + 160
ws = self.root.winfo_screenwidth()
hs = self.root.winfo_screenheight()
x = int((ws / 2) - (width / 2))
y = int((hs / 2) - (height / 2))
self.root.geometry('{}x{}+{}+{}'.format(width, height, x, y))
# 禁止窗体改变大小
self.root.resizable(False, False)
self.root.mainloop()
def quit(self):
self.root.destroy()
示例5: MemberChecker
# 需要导入模块: from tkinter.ttk import Label [as 别名]
# 或者: from tkinter.ttk.Label import configure [as 别名]
class MemberChecker(PanedWindow):
def __init__(self, parent):
PanedWindow.__init__(self, parent, background="white")
self.parent = parent
self.init_data()
self.init_log()
self.init_ui()
self.update_status()
def init_data(self):
self.data_store = api.DataStore()
def init_log(self):
self.entrance_log = entrance_log.EntranceLog()
def init_ui(self):
self.parent.title("Member Checker")
self.columnconfigure(3, weight=3)
self.pack(fill=BOTH, expand=True)
self.input = StringVar()
self.input_entry = Entry(self, textvariable=self.input)
self.input_entry.bind('<Return>', self.submit)
self.input_entry.grid(row=0, column=0, columnspan=3, sticky=E + W)
self.result = StringVar()
self.result_label = Label(self, textvariable=self.result)
self.result_label.grid(row=3, column=0, columnspan=3, sticky=E + W)
self.name = StringVar()
name_label = Label(self, textvariable=self.name)
name_label.grid(row=2, column=0, columnspan=3, sticky=E + W)
self.status = StringVar()
status_label = Label(self, textvariable=self.status)
status_label.grid(row=4, column=0, columnspan=4, sticky=E + W)
submit_button = Button(self, text="Submit", command=self.submit)
submit_button.grid(row=1, column=2)
enter_without_card_button = Button(self, text="Enter without card", command=self.enter_without_card)
enter_without_card_button.grid(row=1, column=0)
enter_member_without_card_button = Button(self, text="Enter member without card",
command=self.enter_member_without_card)
enter_member_without_card_button.grid(row=1, column=1)
self.entrance_log_list = Listbox(self)
self.entrance_log_list.grid(row=0, column=3, rowspan=4, sticky=E + W + S + N)
self.input_entry.focus()
def load_data(self):
if messagebox.askyesno("Load new API Data",
"Are you sure you want to load the new API data? All previous data will be removed. The program might be unresponsive for a few seconds, but don't kill it, please! It has feelings too."):
self.data_store.load_api_data()
def enter_by_identification(self, identification):
member = self.data_store.find_member_by_identification(identification)
if member is None:
if messagebox.askyesno("Not a member",
"This university identification is not registered as a member. Do you want to let them in as a non-member?"):
self.enter_non_member_by_identification(identification)
else:
self.enter_member(member)
def enter_by_barcode(self, barcode):
member = self.data_store.find_member_by_barcode(barcode)
if member is None:
if messagebox.askyesno("Not a member",
"This barcode is not registered as a member. Do you want to let them in as a non-member?"):
self.enter_non_member_by_barcode(barcode)
else:
self.enter_member(member)
def enter_non_member_by_identification(self, identification):
self.entrance_log.enter_non_member_by_identification(identification)
self.enter_non_member()
def enter_non_member_by_barcode(self, barcode):
self.entrance_log.enter_non_member_by_barcode(barcode)
self.enter_non_member()
def enter_without_card(self):
self.clear_result()
self.entrance_log.enter_without_card()
self.enter_non_member()
self.input_entry.focus()
def enter_member(self, member):
inside_result = self.entrance_log.is_member_inside(member)
if inside_result[0]:
if not messagebox.askyesno("Already inside",
"This membership card has already been used to enter at {}. Are you sure you want to register it again? Normally you should let this person enter without card (and bill them accordingly).".format(
inside_result[1])):
return
self.entrance_log.enter_member(member)
self.result.set('Member!')
self.result_label.configure(background='green')
#.........这里部分代码省略.........
示例6: Progression
# 需要导入模块: from tkinter.ttk import Label [as 别名]
# 或者: from tkinter.ttk.Label import configure [as 别名]
class Progression(Frame):
"""Class to display the progress in filling the puzzle."""
def __init__(self, master, number, **kwargs):
kwargs.setdefault('width', 34)
kwargs.setdefault('height', 34)
kwargs.setdefault('style', 'case.TFrame')
Frame.__init__(self, master, **kwargs)
self.grid_propagate(False)
self.rowconfigure(0, weight=1)
self.columnconfigure(0, weight=1)
self.number = number
self._nb = 0
self.label_number = Label(self, style='case.TLabel', text=str(number),
font='Arial 16')
self.label_nb = Label(self, style='case.TLabel', text='0', font='Arial 9')
self.label_number.grid(row=0, column=0, sticky='e', padx=0)
self.label_nb.grid(row=0, column=1, sticky='n')
@property
def nb(self):
return self._nb
@nb.setter
def nb(self, value):
self._nb = value
self.label_nb.configure(text=str(self._nb))
if self._nb < 9:
self.configure(style='case.TFrame')
self.label_number.configure(style='case.TLabel')
self.label_nb.configure(style='case.TLabel')
elif self._nb == 9:
self.configure(style='case_init.TFrame')
self.label_number.configure(style='case_init.TLabel')
self.label_nb.configure(style='case_init.TLabel')
else:
self.configure(style='erreur.TFrame')
self.label_number.configure(style='erreur.TLabel')
self.label_nb.configure(style='erreur.TLabel')
示例7: ErrorSurfaceFrame
# 需要导入模块: from tkinter.ttk import Label [as 别名]
# 或者: from tkinter.ttk.Label import configure [as 别名]
class ErrorSurfaceFrame(LabelFrame):
def __init__(self,parent):
LabelFrame.__init__(self, parent, borderwidth=0)
entryWidth = 7
xPad1 = 30
xPad2 = 5
self.errorXLowerLimitL = Label(self)
self.errorXLowerLimitE = CustomEntry(self,width=entryWidth,justify="right")
self.errorXLowerLimitL.grid(row=0,column=0,padx=(10,xPad2),pady=5,sticky="W")
self.errorXLowerLimitE.grid(row=0,column=1,padx=(xPad2,xPad1),pady=5)
self.errorXUpperLimitL = Label(self)
self.errorXUpperLimitE = CustomEntry(self,width=entryWidth,justify="right")
self.errorXUpperLimitL.grid(row=1,column=0,padx=(10,xPad2),pady=5,sticky="W")
self.errorXUpperLimitE.grid(row=1,column=1,padx=(xPad2,xPad1),pady=5)
self.errorYLowerLimitL = Label(self)
self.errorYLowerLimitE = CustomEntry(self,width=entryWidth,justify="right")
self.errorYLowerLimitL.grid(row=0,column=2,padx=(xPad1,xPad2),pady=5,sticky="W")
self.errorYLowerLimitE.grid(row=0,column=3,padx=(xPad2,xPad1),pady=5)
self.errorYUpperLimitL = Label(self)
self.errorYUpperLimitE = CustomEntry(self,width=entryWidth,justify="right")
self.errorYUpperLimitL.grid(row=1,column=2,padx=(xPad1,xPad2),pady=5,sticky="W")
self.errorYUpperLimitE.grid(row=1,column=3,padx=(xPad2,xPad1),pady=5)
self.errorResolutionL = Label(self,text="Resolution: ")
self.errorResolutionE = CustomEntry(self,width=entryWidth,justify="right")
self.errorResolutionE.insert(0,ERROR_SURFACE_DEFAULT_RESOLUTION)
self.errorResolutionL.grid(row=0,column=4,padx=(xPad1,xPad2),pady=5,sticky="W")
self.errorResolutionE.grid(row=0,column=5,padx=(xPad2,xPad1),pady=5,sticky="E")
self.errorSurfaceB = Button(self,text=" Calculate error surface ")
self.errorSurfaceB.grid(row=1,column=4,columnspan=2,padx=(xPad1,xPad1),sticky="EW")
self.errorSurfaceB.configure(state=tkinter.ACTIVE)
def update(self,xSymbol,ySymbol,xLL,xUL,yLL,yUL):
self.xSymbol = xSymbol
self.ySymbol = ySymbol
self.errorXLowerLimitL.configure(text="Lower limit ("+self.xSymbol+"): ")
self.errorXLowerLimitE.insertNew(xLL)
self.errorXUpperLimitL.configure(text="Upper limit ("+self.xSymbol+"): ")
self.errorXUpperLimitE.insertNew(xUL)
self.errorYLowerLimitL.configure(text="Lower limit ("+self.ySymbol+"): ")
self.errorYLowerLimitE.insertNew(yLL)
self.errorYUpperLimitL.configure(text="Upper limit ("+self.ySymbol+"): ")
self.errorYUpperLimitE.insertNew(yUL)
def getSurfaceParameters(self):
xLowerLimit = helper_functions.validateValue(self.errorXLowerLimitE.get(),
self.xSymbol + " lower limit must be a positive number",
"float",
lowerBound=0)
xUpperLimit = helper_functions.validateValue(self.errorXUpperLimitE.get(),
self.xSymbol + " upper limit must be greater than the lower limit",
"float",
strictLowerBound=xLowerLimit)
yLowerLimit = helper_functions.validateValue(self.errorYLowerLimitE.get(),
self.ySymbol + " lower limit must be a positive number",
"float",
lowerBound=0)
yUpperLimit = helper_functions.validateValue(self.errorYUpperLimitE.get(),
self.ySymbol + " upper limit must be greater than the lower limit",
"float",
strictLowerBound=yLowerLimit)
resolution = helper_functions.validateValue(self.errorResolutionE.get(),
"Resolution must be " + str(ERROR_SURFACE_MIN_RESOLUTION) + " \u2264 x \u2264 " + str(ERROR_SURFACE_MAX_RESOLUTION),
"int",
lowerBound=ERROR_SURFACE_MIN_RESOLUTION,
upperBound=ERROR_SURFACE_MAX_RESOLUTION)
return [xLowerLimit,xUpperLimit,yLowerLimit,yUpperLimit,resolution]
def clear(self):
self.errorXLowerLimitE.insertNew("")
self.errorXUpperLimitE.insertNew("")
self.errorYLowerLimitE.insertNew("")
self.errorYUpperLimitE.insertNew("")
示例8: Sudoku
# 需要导入模块: from tkinter.ttk import Label [as 别名]
# 或者: from tkinter.ttk.Label import configure [as 别名]
class Sudoku(Tk):
def __init__(self, file=None):
Tk.__init__(self, className="Sudoku-Tk")
self.title("Sudoku-Tk")
self.resizable(0, 0)
self.protocol("WM_DELETE_WINDOW", self.quitter)
cst.set_icon(self)
self.columnconfigure(3, weight=1)
# --- style
bg = '#dddddd'
activebg = '#efefef'
pressedbg = '#c1c1c1'
lightcolor = '#ededed'
darkcolor = '#cfcdc8'
bordercolor = '#888888'
focusbordercolor = '#5E5E5E'
disabledfg = '#999999'
disabledbg = bg
button_style_config = {'bordercolor': bordercolor,
'background': bg,
'lightcolor': lightcolor,
'darkcolor': darkcolor}
button_style_map = {'background': [('active', activebg),
('disabled', disabledbg),
('pressed', pressedbg)],
'lightcolor': [('pressed', darkcolor)],
'darkcolor': [('pressed', lightcolor)],
'bordercolor': [('focus', focusbordercolor)],
'foreground': [('disabled', disabledfg)]}
style = Style(self)
style.theme_use(cst.STYLE)
style.configure('TFrame', background=bg)
style.configure('TLabel', background=bg)
style.configure('TScrollbar', gripcount=0, troughcolor=pressedbg,
**button_style_config)
style.map('TScrollbar', **button_style_map)
style.configure('TButton', **button_style_config)
style.map('TButton', **button_style_map)
style.configure('TCheckutton', **button_style_config)
style.map('TCheckutton', **button_style_map)
self.option_add('*Toplevel.background', bg)
self.option_add('*Menu.background', bg)
self.option_add('*Menu.activeBackground', activebg)
self.option_add('*Menu.activeForeground', "black")
self.configure(bg=bg)
style.configure("bg.TFrame", background="grey")
style.configure("case.TFrame", background="white")
style.configure("case.TLabel", background="white", foreground="black")
style.configure("case_init.TFrame", background="lightgrey")
style.configure("case_init.TLabel", background="lightgrey", foreground="black")
style.configure("erreur.TFrame", background="white")
style.configure("erreur.TLabel", background="white", foreground="red")
style.configure("solution.TFrame", background="white")
style.configure("solution.TLabel", background="white", foreground="blue")
style.configure("pause.TLabel", foreground="grey", background='white')
# --- images
self.im_erreur = open_image(cst.ERREUR)
self.im_pause = open_image(cst.PAUSE)
self.im_restart = open_image(cst.RESTART)
self.im_play = open_image(cst.PLAY)
self.im_info = open_image(cst.INFO)
self.im_undo = open_image(cst.UNDO)
self.im_redo = open_image(cst.REDO)
self.im_question = open_image(cst.QUESTION)
# --- timer
self.chrono = [0, 0]
self.tps = Label(self, text=" %02i:%02i" % tuple(self.chrono),
font="Arial 16")
self.debut = False # la partie a-t-elle commencée ?
self.chrono_on = False # le chrono est-il en marche ?
# --- buttons
self.b_pause = Button(self, state="disabled", image=self.im_pause,
command=self.play_pause)
self.b_restart = Button(self, state="disabled", image=self.im_restart,
command=self.recommence)
self.b_undo = Button(self, image=self.im_undo, command=self.undo)
self.b_redo = Button(self, image=self.im_redo, command=self.redo)
# --- tooltips
self.tooltip_wrapper = TooltipWrapper(self)
self.tooltip_wrapper.add_tooltip(self.b_pause, _("Pause game"))
self.tooltip_wrapper.add_tooltip(self.b_restart, _("Restart game"))
self.tooltip_wrapper.add_tooltip(self.b_undo, _("Undo"))
self.tooltip_wrapper.add_tooltip(self.b_redo, _("Redo"))
# --- numbers
frame_nb = Frame(self, style='bg.TFrame', width=36)
self.progression = []
for i in range(1, 10):
self.progression.append(Progression(frame_nb, i))
self.progression[-1].pack(padx=1, pady=1)
#.........这里部分代码省略.........