def insert_ttk_label(self, anchor: tk.W or tk.CENTER or tk.E or str=None, background: str="", font: font.Font=None, foreground: str="", justify: tk.LEFT or tk.CENTER or tk.RIGHT or str=None, padding: list=[], relief: tk.FLAT or tk.RAISED or tk.SUNKEN or tk.GROOVE or tk.RIDGE or str="flat", text: str="", wraplength: int=0, index: int or str="end", *args, **kwargs):
"""Insert a ttk.Label into the game."""
widget = ttk.Label(self.text, anchor=anchor, background=background, font=font, foreground=foreground, justify=justify, padding=padding, relief=relief, text=text, wraplength=wraplength, **kwargs)
self.text.window_create(index, window=widget)
return widget
python类Label()的实例源码
def add_combobox(self, key, choices, text, *, case_sensitive=True):
"""Add a ``ttk.Combobox`` that sets an option to a string.
The combobox will contain each string in *choices*.
A `validator callback <Validating>`_ that ensures the value is
in *choices* is also added. If *case_sensitive* is False,
:meth:`str.casefold` is used when comparing the strings.
"""
def validator(value):
if case_sensitive:
ok = (value in choices)
else:
ok = (value.casefold() in map(str.casefold, choices))
if not ok:
raise InvalidValue("%r is not a valid %r value"
% (value, key))
self.connect(key, validator)
frame = self.add_frame(key)
ttk.Label(frame, text=text).pack(side='left')
ttk.Combobox(frame, values=choices,
textvariable=self.get_var(key)).pack(side='right')
def add_spinbox(self, key, minimum, maximum, text):
"""
Add a :class:`utils.Spinbox <porcupine.utils.Spinbox>` that sets
an option to an integer.
The *minimum* and *maximum* arguments are used as the bounds for
the spinbox. A `validator callback <Validating>`_ that makes
sure the value is between them is also added.
Note that *minimum* and *maximum* are inclusive, so
``minimum=3, maximum=5`` means that 3, 4 and 5 are valid values.
"""
def validator(value):
if value < minimum:
raise InvalidValue("%r is too small" % value)
if value > maximum:
raise InvalidValue("%r is too big" % value)
self.connect(key, validator)
frame = self.add_frame(key)
ttk.Label(frame, text=text).pack(side='left')
utils.Spinbox(frame, textvariable=self.get_var(key, tkinter.IntVar),
from_=minimum, to=maximum).pack(side='right')
def make_please_wait_window(self):
window = self.please_wait_window = tkinter.Toplevel()
window.transient(porcupine.get_main_window())
window.title("Pasting...")
window.geometry('350x150')
window.resizable(False, False)
# disable the close button, there's no good way to cancel this
# forcefully :(
window.protocol('WM_DELETE_WINDOW', (lambda: None))
content = ttk.Frame(window)
content.pack(fill='both', expand=True)
label = ttk.Label(
content, font=('', 12, ''),
text=("Pasting to %s, please wait..." % self.pastebin_name))
label.pack(expand=True)
progressbar = ttk.Progressbar(content, mode='indeterminate')
progressbar.pack(fill='x', padx=15, pady=15)
progressbar.start()
def __init__(self, master, title, main, sub, **kwargs):
super().__init__(master=master, **kwargs)
self.configure(borderwidth=3, relief='groove')
self._title_font = font.Font(family='mono', size=-15)
self._main_font = font.Font(family='mono', size=-30, weight='bold')
self._sub_font = font.Font(family='mono', size=-15)
self._title_string = StringVar(value=title)
self._title_label = ttk.Label(self, textvariable=self._title_string, font=self._title_font)
self._main_string = StringVar(value=main)
self._main_label = ttk.Label(self, textvariable=self._main_string, font=self._main_font)
self._sub_string = StringVar(value=sub)
self._sub_label = ttk.Label(self, textvariable=self._sub_string, font=self._sub_font)
self._title_label.grid(column=0, row=0, sticky=N + S + W, padx=15, pady=5)
self._main_label.grid(column=0, row=1, sticky=N + S + W, padx=10, pady=5)
self._sub_label.grid(column=0, row=2, sticky=N + S + W, padx=15, pady=5)
self.columnconfigure(0, weight=1)
self.rowconfigure(1, weight=1)
def __init__(self, master, **kwargs):
super().__init__(master, **kwargs)
self.content_frame = ttk.Frame(self)
self.lb_title = ttk.Label(self.content_frame, text='Lesson paused')
self.button_frame = ttk.Frame(self.content_frame)
self.bt_continue = ttk.Button(self.button_frame, text='Continue', default='active', command=self.on_continue)
self.bt_restart = ttk.Button(self.button_frame, text='Restart')
self.bt_abort = ttk.Button(self.button_frame, text='Abort')
self.content_frame.grid(column=0, row=0)
self.lb_title.grid(column=0, row=0, pady=3)
self.button_frame.grid(column=0, row=1, pady=10)
self.bt_continue.grid(column=0, row=1, pady=3)
self.bt_restart.grid(column=0, row=2, pady=3)
self.bt_abort.grid(column=0, row=3, pady=3)
self.columnconfigure(0, weight=1)
self.rowconfigure(0, weight=1)
self.focus_set()
def invalidInventoryPopup(self, msg, *mainFuncs):
"""
Creates a popupwindow and binds the button to multiple functions
:param msg: Text message displayed in the popupwindow
:type msg: str
:param mainFuncs: List of functions to be run when the user clicks OK
"""
window = Tk()
window.wm_title('Invalid Inventory File')
message = ttk.Label(window, text=msg)
message.grid(row=0, column=0, columnspan=2, pady=10, padx=10, sticky=tkinter.N + tkinter.S)
okButton = ttk.Button(window, text="OK", command=lambda: self.combine_funcs(window.destroy(), window.quit()))
okButton.grid(row=1, column=1, sticky=tkinter.N + tkinter.S)
window.mainloop()
def test_sashpos(self):
self.assertRaises(tkinter.TclError, self.paned.sashpos, None)
self.assertRaises(tkinter.TclError, self.paned.sashpos, '')
self.assertRaises(tkinter.TclError, self.paned.sashpos, 0)
child = ttk.Label(self.paned, text='a')
self.paned.add(child, weight=1)
self.assertRaises(tkinter.TclError, self.paned.sashpos, 0)
child2 = ttk.Label(self.paned, text='b')
self.paned.add(child2)
self.assertRaises(tkinter.TclError, self.paned.sashpos, 1)
self.paned.pack(expand=True, fill='both')
self.paned.wait_visibility()
curr_pos = self.paned.sashpos(0)
self.paned.sashpos(0, 1000)
self.assertNotEqual(curr_pos, self.paned.sashpos(0))
self.assertIsInstance(self.paned.sashpos(0), int)
def __init__(self, master, **kw):
super().__init__(master)
# self.grid_propagate(0)
# self.columnconfigure(0, weight=1)
# self.rowconfigure(0, weight=1)
self.var = kw.get('variable', IntVar())
kw['variable'] = self.var
kw['from_'] = ConfidenceLevel.Low.value
kw['to'] = ConfidenceLevel.VeryHigh.value
# kw['command'] = self.scale_change
kw['orient'] = HORIZONTAL
self.lbl_scale = Label(self)
self.scale = Scale(self, **kw)
self.scale_font = tkfont.nametofont(Style().lookup('TLabel', 'font')).copy()
self.scale_font.config(weight=tkfont.BOLD, size=9)
self.lbl_scale.config(font=self.scale_font, width=3, anchor=CENTER)
self.var.trace_variable('w', lambda a, b, c: self.scale_change())
self.scale.grid(row=0, column=0, sticky='ns')
self.lbl_scale.grid(row=0, column=1, sticky='ns', padx=(3, 0))
def setup_tab2(tab):
# new frame
new_frame = ttk.LabelFrame(tab, text='New Project Name')
new_frame.grid(columnspan=2, row=0, padx=5, pady=5, sticky='ew')
# New Project
name = tk.StringVar
name_entered = ttk.Entry(new_frame, width=19, textvariable=name)
name_entered.grid(column=0, row=0, padx=6, pady=5)
name_entered.focus()
# spacer
spacer_label = ttk.Label(new_frame, text='')
spacer_label.grid(columnspan=2, row=1, padx=5, pady=5)
# add button and commands
def add_command():
add_project(name_entered.get())
spacer_label.configure(text='Project was added!', foreground='green')
name_entered.delete(0, "end")
setup_tab1(TAB_1)
TAB_1.update()
add_button = ttk.Button(tab, text='Add New Project', command=add_command)
add_button.grid(columnspan=2, row=3, pady=5)
def _show_history(self):
history_window = self._create_window('History')
history_window.resizable(height=False, width=False)
history_window.geometry('{0}x{1}+{2}+{3}'.format(200, 90, 300, 150))
history_label = ttk.Label(
history_window, text='Enter number: ', background=self.bg)
history_label.grid(row=0, column=0, padx=5, pady=5)
history_entry = ttk.Entry(history_window, width=10)
history_entry.grid(row=0, column=1, padx=5, pady=5)
history_entry.focus_set()
help_text = ttk.Label(history_window, text='Number of files (in history) to view.\n\nPress Enter when done.',
background=self.bg, foreground="#C0C0C0", anchor=CENTER, justify='center')
help_text.grid(row=1, column=0, columnspan=2, padx=5, pady=5)
history_window.bind('<Return>',
lambda event, entry_widget=history_entry, window=history_window: self._evaluate(event, entry_widget, window))
history_window.bind('<KP_Enter>',
lambda event, entry_widget=history_entry, window=history_window: self._evaluate(event, entry_widget, window))
def restrict_access_button(self, gs):
"""Expand frame to reveal options when Restrict Read Access is selected."""
if self.access_button_var.get() == 1:
self.group_name_label = ttk.Label(self.access_frame,
width=20,
anchor=tk.E,
text='Group Name ')
self.group_name_label.grid(row=2, column=0, sticky='e')
self.group_name_label.grid_configure(pady=5)
self.group_name_var = tk.StringVar()
self.group_name_entry = ttk.Entry(self.access_frame,
width=20,
textvariable=self.group_name_var)
self.group_name_entry.grid(row=2, column=1, sticky='w')
self.group_name_entry.grid_configure(pady=5)
self.group_name_var.set('member')
else:
self.group_name_label.destroy()
self.group_name_entry.destroy()
def restrict_access_button(self, gs):
"""Expand frame to reveal options when Restrict Read Access is selected."""
if self.access_button_var.get() == 1:
self.group_name_label = ttk.Label(self.access_frame,
width=15,
anchor=tk.E,
text='Group Name ')
self.group_name_label.grid(row=2, column=0, sticky='e')
self.group_name_label.grid_configure(pady=5)
self.group_name_var = tk.StringVar()
self.group_name_entry = ttk.Entry(self.access_frame,
width=15,
textvariable=self.group_name_var)
self.group_name_entry.grid(row=2, column=1, sticky='w')
self.group_name_entry.grid_configure(pady=5)
self.group_name_var.set('member')
else:
self.group_name_label.destroy()
self.group_name_entry.destroy()
def calenderPlaceWidget(self):
#Header Frame
calenderFrame = ttk.Frame(self)
leftMonthChangeButton = ttk.Button(calenderFrame, style='L.TButton', command=self.setPreviousMonth)
rightMonthChangeButton = ttk.Button(calenderFrame, style='R.TButton', command=self.setNextMonth)
self.calenderHeader = ttk.Label(calenderFrame, width=15, anchor='center')
self.calenderMainView = ttk.Treeview(show='', selectmode='none', height=7, style='Calendar.Treeview')
#Pack Header
calenderFrame.pack(in_=self, side='top', pady=4, anchor='center')
leftMonthChangeButton.grid(in_=calenderFrame)
self.calenderHeader.grid(in_=calenderFrame, column=1, row=0, padx=12)
rightMonthChangeButton.grid(in_=calenderFrame, column=2, row=0)
self.calenderMainView.pack(in_=self, fill='x', side='top')
def __init__(self, parent):
"""Send messages from the bot
Args:
parent:
"""
super(ChatFrame, self).__init__(parent, padding=8, text="Chat")
self.channel = tk.StringVar()
self.message = tk.StringVar()
self.channel_frame = ttk.Frame(self)
self.channel_frame.grid(column=0, row=0, sticky="W E")
self.channel_label = ttk.Label(self.channel_frame, text="Channel ID:")
self.channel_label.grid(column=0, row=0, sticky="W E")
self.channel_box = ttk.Entry(self.channel_frame, textvariable=self.channel)
self.channel_box.grid(column=0, row=1, sticky="W E")
self.channel_frame.columnconfigure(0, weight=1)
self.message_frame = ttk.Frame(self)
self.message_frame.grid(column=0, row=1, pady=8, sticky="W E")
self.message_label = ttk.Label(self.message_frame, text="Message:")
self.message_label.grid(column=0, row=0, sticky="W E")
self.message_box = ttk.Entry(self.message_frame, textvariable=self.message)
self.message_box.grid(column=0, row=1, sticky="W E")
self.message_frame.columnconfigure(0, weight=1)
self.send_button = ttk.Button(self, command=lambda: self.add_current_message(), text="Send")
self.send_button.grid(column=0, row=2, sticky="W")
self.columnconfigure(0, weight=1)
def __init__(self, parent):
"""
Create a new UI for the module
Args:
parent: A tk or ttk object
"""
super(ModuleUIFrame, self).__init__(parent)
self.columnconfigure(0, weight=1)
self.rowconfigure(1, weight=1)
# Set default values
from ....datatools import get_data
data = get_data()
# API Frame
api_frame = ttk.LabelFrame(self, padding=8, text="Google API")
api_frame.grid(row=0, column=0, sticky="W E N S")
api_frame.columnconfigure(0, weight=1)
# Add key fields
self.google_api_key = tk.StringVar()
ttk.Label(api_frame, text="Google API Key").grid(column=0, row=0, sticky="W E N S")
ttk.Entry(api_frame, textvariable=self.google_api_key).grid(
column=0, row=1, padx=0, pady=4, sticky="W E N S")
self.soundcloud_client_id = tk.StringVar()
ttk.Label(api_frame, text="SoundCloud Client ID").grid(column=0, row=2, sticky="W E N S")
ttk.Entry(api_frame, textvariable=self.soundcloud_client_id).grid(
column=0, row=3, padx=0, pady=4, sticky="W E N S")
ttk.Button(api_frame, command=lambda: self.update_keys(), text="Update API Data").grid(
column=0, row=4, padx=0, pady=4, sticky="W E N S")
if "google_api_key" in data["discord"]["keys"]:
self.google_api_key.set(data["discord"]["keys"]["google_api_key"])
if "soundcloud_client_id" in data["discord"]["keys"]:
self.soundcloud_client_id.set(data["discord"]["keys"]["soundcloud_client_id"])
def clear_modules(self):
"""Clears all modules from the list"""
for child in self.module_selection.winfo_children():
child.destroy()
self.clear_ui()
tk.Label(self.module_ui, text="Start Modis and select a module").grid(
column=0, row=0, padx=0, pady=0, sticky="W E N S")
if self.current_button is not None:
self.current_button.config(bg="white")
self.module_buttons = {}
self.current_button = None
def module_selected(self, module_name, module_ui):
"""
Called when a module is selected
Args:
module_name (str): The name of the module
module_ui: The function to call to create the module's UI
"""
if self.current_button == self.module_buttons[module_name]:
return
self.module_buttons[module_name].config(bg="#cacaca")
if self.current_button is not None:
self.current_button.config(bg="white")
self.current_button = self.module_buttons[module_name]
self.clear_ui()
try:
# Create the UI
module_ui_frame = ModuleUIBaseFrame(self.module_ui, module_name, module_ui)
module_ui_frame.grid(column=0, row=0, sticky="W E N S")
except Exception as e:
logger.error("Could not load UI for {}".format(module_name))
logger.exception(e)
# Create a error UI
tk.Label(self.module_ui, text="Could not load UI for {}".format(module_name)).grid(
column=0, row=0, padx=0, pady=0, sticky="W E N S")
def __init__(self, parent, module_name, module_ui):
"""
Create a new base for a module UI
Args:
parent: A tk or ttk object
module_name (str): The name of the module
module_ui: The _ui.py file to add for the module
"""
super(ModuleUIBaseFrame, self).__init__(parent, padding=8)
self.columnconfigure(0, weight=1)
self.rowconfigure(1, weight=1)
if module_ui is not None:
# Module UI frame
module_ui.ModuleUIFrame(self).grid(row=0, column=0, sticky="W E N S")
else:
logger.debug("No _ui.py found for '{}'".format(module_name))
# Help frame
help_frame = ttk.LabelFrame(self, padding=8, text="Help")
help_frame.grid(row=1, column=0, sticky="W E N S")
help_frame.columnconfigure(0, weight=1)
help_frame.rowconfigure(0, weight=1)
# Find the help path
_dir = os.path.realpath(
os.path.join(os.getcwd(), os.path.dirname(__file__)))
help_path = "{}/modules/{}/{}".format(_dir, module_name, "_help.json")
if os.path.isfile(help_path):
# Load the text
helptools.add_help_text(help_frame, help_path)
else:
# Default message
tk.Label(help_frame, text="No _help.json file found for '{}'".format(module_name)).grid(row=0, column=0,
sticky="W E N S")