本文整理汇总了Python中tkinter.Canvas.configure方法的典型用法代码示例。如果您正苦于以下问题:Python Canvas.configure方法的具体用法?Python Canvas.configure怎么用?Python Canvas.configure使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tkinter.Canvas
的用法示例。
在下文中一共展示了Canvas.configure方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run_pinballview
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import configure [as 别名]
def run_pinballview(width, height, configuration):
"""
Changed from original Pierre-Luc Bacon implementation to reflect
the visualization changes in the PinballView Class.
"""
width, height = float(width), float(height)
master = Tk()
master.title('RLPY Pinball')
screen = Canvas(master, width=500.0, height=500.0)
screen.configure(background='LightGray')
screen.pack()
environment = PinballModel(configuration)
environment_view = PinballView(screen, width, height, environment)
actions = [
PinballModel.ACC_X,
PinballModel.DEC_Y,
PinballModel.DEC_X,
PinballModel.ACC_Y,
PinballModel.ACC_NONE]
done = False
while not done:
user_action = np.random.choice(actions)
environment_view.blit()
if environment.episode_ended():
done = True
if environment.take_action(user_action) == environment.END_EPISODE:
done = True
environment_view.blit()
screen.update()
示例2: Mjolnir
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import configure [as 别名]
class Mjolnir(KRCCModule):
def __init__(self, root):
super().__init__()
self.canvas = Canvas(root)
self.canvas.pack(side=RIGHT, fill=BOTH, expand=True)
self.canvas.configure(background='#000000')
def __del__(self):
self.canvas.destroy()
def run(self):
while not self.terminate:
pass
def name(self):
return 'Mjolnir'
示例3: Visual
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import configure [as 别名]
class Visual(Frame):
'''Class that takes a world as argument and present it graphically
on a tkinter canvas.'''
def __init__(self):
'''
Sets up a simulation GUI in tkinter.
'''
Frame.__init__(self)
self.master.title("The Schelling Segregation Model in Python")
self.master.wm_resizable(0, 0)
self.grid()
self.movement_possible = True
# --------------------------------------- #
# --------- FRAMES FOR GUI -------------- #
# --------------------------------------- #
# The pane for user values
self._entryPane = Frame(self,
borderwidth=5,
relief='sunken')
self._entryPane.grid(row=0, column=0, sticky='n')
# The buttons pane
self._buttonPane = Frame(self, borderwidth=5)
self._buttonPane.grid(row=1, column=0, sticky='n')
# A temp pane where graph is located, just for cosmetic reasons
width, height = 425, 350
self._graph = Canvas(self,
width=width,
height=height,
background="black")
self._graph.configure(relief='sunken', border=2)
self._graph.grid(row=3, column=0)
# The pane where the canvas is located
self._animationPane = Frame(self,
borderwidth=5,
relief='sunken')
self._animationPane.grid(row=0, column=1,
rowspan=4, pady=10,
sticky="n")
# --------------------------------------- #
# --------- FILLING THE FRAMES ---------- #
# --------------------------------------- #
self._canvas() # Create graphics canvas
self._entry() # Create entry widgets
self._buttons() # Create button widgets
def _plot_setup(self, time):
'''Method for crudely annotating the graph window.'''
time = time
# Main plot
width, height = 425, 350
y0 = -time/10
self._graph = Canvas(self, width=width,
height=height,
background="black",
borderwidth=5)
self._graph.grid(row=3, column=0)
self.trans = Plotcoords(width, height, y0, -0.2, time, 1.3)
x, y = self.trans.screen(time // 2, 1.2)
x1, y1 = self.trans.screen(time // 2, 1.13)
self._graph.create_text(x, y,
text="% Happy",
fill="green",
font="bold 12")
self._graph.create_text(x1, y1,
text="% Unhappy",
fill="red",
font="bold 12")
# Line x-axis
x, y = self.trans.screen((-5 * (time / 100)), -0.05)
x1, y = self.trans.screen(time, -0.05)
self._graph.create_line(x, y, x1, y, fill="white", width=1.5)
# Text x-axis
x_text, y_text = self.trans.screen(time / 2, -0.15)
self._graph.create_text(x_text, y_text,
text="Time",
fill="white",
font="bold 12")
# Line y-axis
x, y = self.trans.screen((-0.5 * (time / 100)), -0.05)
x, y1 = self.trans.screen((-5 * (time / 100)), 1)
self._graph.create_line(x, y, x, y1, fill="white", width=1.5)
def _entry(self):
'''Method for creating widgets for collecting user input.'''
# N (no of turtles)
#.........这里部分代码省略.........
示例4: RadiobuttonEntry
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import configure [as 别名]
class RadiobuttonEntry(ttk.Frame):
"""State entry for all DMs, and controls for adding the infeasibles.
Uses a set of RadioButtonSeries elements.
"""
def __init__(self, master, conflict):
"""Initialize the widget."""
ttk.Frame.__init__(self, master)
self.conflict = conflict
self.dmLookup = {dm.name: dm for dm in self.conflict.decisionMakers}
dmNames = tuple(self.dmLookup.keys())
self.activeDMname = StringVar(value=dmNames[0])
self.activeDM = self.dmLookup[dmNames[0]]
dmSelLabel = ttk.Label(self, text="Decision Maker")
dmSelLabel.grid(column=0, row=0)
self.dmSelector = ttk.Combobox(self, textvariable=self.activeDMname,
values=dmNames, state='readonly')
self.dmSelector.grid(column=1, row=0, sticky=NSEW)
self.dmSelector.bind('<<ComboboxSelected>>', self.dmSel)
self.rbeCanvas = Canvas(self)
self.rdBtnFrame = ttk.Frame(self.rbeCanvas)
self.scrollY = ttk.Scrollbar(self, orient=VERTICAL,
command=self.rbeCanvas.yview)
self.rbeCanvas.grid(column=0, row=1, columnspan=2, sticky=NSEW)
self.scrollY.grid(column=2, row=1, sticky=NSEW)
self.rbeCanvas.configure(yscrollcommand=self.scrollY.set)
self.canvWindow = self.rbeCanvas.create_window(
(0, 0), window=self.rdBtnFrame, anchor='nw')
self.rowconfigure(1, weight=1)
self.entryText = StringVar(value='')
vcmd = self.register(self.onValidate)
self.entryBx = ttk.Entry(self, textvariable=self.entryText,
validate="key",
validatecommand=(vcmd, '%S', '%P'))
self.entryBx.grid(column=0, row=2, columnspan=2, sticky=NSEW)
self.entryBx.bind('<Return>', self.generateAdd)
self.warnText = StringVar(value='')
self.addBtn = ttk.Button(self, text='Remove as Misperceived Condition',
command=self.generateAdd)
self.mutExBtn = ttk.Button(self,
text='Perceived as Mutually Exclusive',
command=self.generateMutEx)
self.warnLab = ttk.Label(self, textvariable=self.warnText)
self.warnLab.grid(column=0, row=3, sticky=NSEW)
self.addBtn.grid(column=0, row=4, columnspan=2, sticky=NSEW)
self.mutExBtn.grid(column=0, row=5, columnspan=2, sticky=NSEW)
self.reloadOpts()
def resize(self, event=None):
"""Resize the scroll region of the main canvas element."""
self.rbeCanvas.configure(scrollregion=self.rbeCanvas.bbox("all"))
self.rbeCanvas["width"] = self.rbeCanvas.bbox("all")[2]
def generateAdd(self, *args):
"""Prompt response to addition of an infeasible state."""
self.event_generate('<<addMisperceived>>')
def generateMutEx(self, *args):
"""Prompt response to addition of a mutually exclusive set."""
self.event_generate('<<AddMutEx>>')
def reloadOpts(self):
"""Reload all options for all DMs."""
self.rbeCanvas.delete(self.canvWindow)
self.rdBtnFrame.destroy()
self.rdBtnFrame = ttk.Frame(self.rbeCanvas)
self.canvWindow = self.rbeCanvas.create_window(
(0, 0), window=self.rdBtnFrame, anchor='nw')
self.rdBtnFrame.bind('<<RdBtnChg>>', self.rdBtnChgCmd)
self.rdBtnFrame.bind("<Configure>", self.resize)
self.rdBtnSrs = []
self.stringVarList = []
for x, dm in enumerate(self.conflict.decisionMakers):
a = RadiobuttonSeries(self.rdBtnFrame, dm)
self.rdBtnSrs.append(a)
a.setOpts(dm.options)
a.grid(column=0, row=int(x), sticky=NSEW)
self.stringVarList += a.stringVarList
self.rdBtnChgCmd()
def setStates(self, dashOne):
"""Change the condition selected on the radio buttons."""
if len(dashOne) != len(self.stringVarList):
raise Exception('string length does not match number '
#.........这里部分代码省略.........
示例5: Edit
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import configure [as 别名]
class Edit(Frame):
def __init__(self, master, valves):
Frame.__init__(self, master, bg='sky blue', width=1366, height=768)
self.master = master
self.canvas = Canvas(self, height=630, width=1320, bg='sky blue')
self.frame = Frame(self.canvas, bg='sky blue')
self.scrollbar = Scrollbar(self, orient='vertical', command=self.canvas.yview)
self.scrollbar.configure(activebackground='DarkRed', background='red', width=40)
self.canvas.configure(yscrollcommand=self.scrollbar.set, scrollregion=[0, 0, 1366, 800])
self.scrollbar.pack(side='right', fill='y')
self.canvas.pack(side='left')
self.canvas.create_window((0, 0), window=self.frame, anchor='nw')
self.valves = valves
self.frame.config(bg='sky blue')
index = 0
while index < 10:
self.frame.grid_rowconfigure(index, minsize=80)
self.frame.grid_columnconfigure(index, minsize=30)
index += 1
self.frame.grid_columnconfigure(3, minsize=130)
self.frame.grid_columnconfigure(6, minsize=130)
interval = Label(self.frame, text='RUN', width=6, font=('Lucida Console', 30))
interval.grid(row=0, column=2)
interval.config(bg='sky blue', fg='RoyalBlue4')
delay = Label(self.frame, text='DELAY', width=6, font=('Lucida Console', 30))
delay.grid(row=0, column=5)
delay.config(bg='sky blue', fg='RoyalBlue4')
self.seconds = [IntVar(),
IntVar(),
IntVar(),
IntVar(),
IntVar(),
IntVar(),
IntVar(),
IntVar(),
IntVar(),
IntVar(),
IntVar(),
IntVar(),
IntVar(),
IntVar(),
IntVar(),
IntVar(),
IntVar(),
IntVar()]
for each in self.seconds:
each.set(0)
self.set_seconds()
self.valve_label = [Label(self.frame, textvariable=self.valves[0].get_name()),
Label(self.frame, textvariable=self.valves[1].get_name()),
Label(self.frame, textvariable=self.valves[2].get_name()),
Label(self.frame, textvariable=self.valves[3].get_name()),
Label(self.frame, textvariable=self.valves[4].get_name()),
Label(self.frame, textvariable=self.valves[5].get_name()),
Label(self.frame, textvariable=self.valves[6].get_name()),
Label(self.frame, textvariable=self.valves[7].get_name())
]
row = 1
for each in self.valve_label:
each.grid(row=row, column=0)
each.config(width=8, font=('Lucida Console', 30), bg='sky blue', fg='RoyalBlue4')
row += 1
self.minus_image = PhotoImage(file="img/minus.png").subsample(x=5, y=5)
self.minusInterval = [Button(self.frame, image=self.minus_image, command=lambda: self.subtract(0)),
Button(self.frame, image=self.minus_image, command=lambda: self.subtract(1)),
Button(self.frame, image=self.minus_image, command=lambda: self.subtract(2)),
Button(self.frame, image=self.minus_image, command=lambda: self.subtract(3)),
Button(self.frame, image=self.minus_image, command=lambda: self.subtract(4)),
Button(self.frame, image=self.minus_image, command=lambda: self.subtract(5)),
Button(self.frame, image=self.minus_image, command=lambda: self.subtract(6)),
Button(self.frame, image=self.minus_image, command=lambda: self.subtract(7)),
]
row = 1
for each in self.minusInterval:
each.grid(row=row, column=1)
each.config(bg='SkyBlue4', activebackground='midnight blue', fg='white')
row += 1
self.labelInterval = [Label(self.frame, textvariable=self.seconds[0]),
Label(self.frame, textvariable=self.seconds[1]),
Label(self.frame, textvariable=self.seconds[2]),
Label(self.frame, textvariable=self.seconds[3]),
Label(self.frame, textvariable=self.seconds[4]),
Label(self.frame, textvariable=self.seconds[5]),
Label(self.frame, textvariable=self.seconds[6]),
Label(self.frame, textvariable=self.seconds[7])]
#.........这里部分代码省略.........
示例6: Preferences
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import configure [as 别名]
class Preferences(Frame):
def __init__(self, master, valves):
Frame.__init__(self, master, bg='sky blue', width=1366, height=768)
self.master = master
self.canvas = Canvas(self, height=640, width=1300, bg='sky blue')
self.frame = Frame(self.canvas, bg='sky blue')
self.frame.bind('<Button-1>', self.process_click_out)
self.scrollbar = Scrollbar(self, orient='vertical', command=self.canvas.yview)
self.scrollbar.configure(activebackground='DarkRed', background='red', width=40)
self.canvas.configure(yscrollcommand=self.scrollbar.set, scrollregion=[0, 0, 1366, 2100])
self.scrollbar.pack(side='right', fill='y')
self.canvas.pack(side='left')
self.canvas.create_window((0, 0), window=self.frame, anchor='nw')
self.keyboard = Keyboard(self.master)
self.valves = valves
self.frame.config(bg='sky blue')
index = 0
while index < 25:
self.frame.grid_rowconfigure(index, minsize=80)
self.frame.grid_columnconfigure(index, minsize=150)
index += 1
num_label = [Label(self.frame, text='1'),
Label(self.frame, text='2'),
Label(self.frame, text='3'),
Label(self.frame, text='4'),
Label(self.frame, text='5'),
Label(self.frame, text='6'),
Label(self.frame, text='7'),
Label(self.frame, text='8'),
]
row = 1
for each in num_label:
each.grid(row=row, column=0)
each.config(width=3, font=('Lucida Console', 30), bg='sky blue', fg='RoyalBlue4')
row += 3
text_label = [Label(self.frame, text='VALVE 1: '),
Label(self.frame, text='ACTION A: '),
Label(self.frame, text='ACTION B: '),
Label(self.frame, text='VALVE 2: '),
Label(self.frame, text='ACTION A: '),
Label(self.frame, text='ACTION B: '),
Label(self.frame, text='VALVE 3: '),
Label(self.frame, text='ACTION A: '),
Label(self.frame, text='ACTION B: '),
Label(self.frame, text='VALVE 4: '),
Label(self.frame, text='ACTION A: '),
Label(self.frame, text='ACTION B: '),
Label(self.frame, text='VALVE 5: '),
Label(self.frame, text='ACTION A: '),
Label(self.frame, text='ACTION B: '),
Label(self.frame, text='VALVE 6: '),
Label(self.frame, text='ACTION A: '),
Label(self.frame, text='ACTION B: '),
Label(self.frame, text='VALVE 7: '),
Label(self.frame, text='ACTION A: '),
Label(self.frame, text='ACTION B: '),
Label(self.frame, text='VALVE 8: '),
Label(self.frame, text='ACTION A: '),
Label(self.frame, text='ACTION B: ')
]
row = 1
for each in text_label:
each.grid(row=row, column=1)
each.config(width=12, font=('Lucida Console', 30), bg='sky blue', fg='RoyalBlue4')
row += 1
self.valve_label = [Label(self.frame, textvariable=self.valves[0].get_name()),
Label(self.frame, textvariable=self.valves[1].get_name()),
Label(self.frame, textvariable=self.valves[2].get_name()),
Label(self.frame, textvariable=self.valves[3].get_name()),
Label(self.frame, textvariable=self.valves[4].get_name()),
Label(self.frame, textvariable=self.valves[5].get_name()),
Label(self.frame, textvariable=self.valves[6].get_name()),
Label(self.frame, textvariable=self.valves[7].get_name())]
row = 1
for each in self.valve_label:
each.grid(row=row, column=2)
each.config(width=12, font=('Lucida Console', 30), bg='sky blue', fg='RoyalBlue4', anchor='w')
each.bind('<Button-1>', self.process_click_out)
row += 3
self.entry_field = [Entry(self.frame, text=''),
Entry(self.frame, text=''),
Entry(self.frame, text=''),
#.........这里部分代码省略.........
示例7: mainGUI
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import configure [as 别名]
class mainGUI(Frame, bootloader, GuiController):
""" Contains the main view for the application """
def __init__(self):
""" Create the initial application GUI environment (tool bars, and other static elements) """
Frame.__init__(self, self.root)
self.thread_entry_field = '' # Hold both search string, and drives autoRefresh logic
self.menuBar = Menu()
self.fileMenu = Menu(self.menuBar, tearoff=0)
self.menuBar.add_cascade(label="File", menu=self.fileMenu, underline=1)
self.fileMenu.add_command(label="Quit", command=self.root.destroy, underline=1)
self.optionsMenu = Menu(self.menuBar, tearoff=0)
self.menuBar.add_cascade(label="Options", menu=self.optionsMenu)
self.optionsMenu.add_command(label="Settings", command=self.editSettings, underline=1)
self.helpMenu = Menu(self.menuBar, tearoff=0)
self.menuBar.add_cascade(label="Help", menu=self.helpMenu)
self.helpMenu.add_command(label="Help", command=self.program_help, underline=1)
self.helpMenu.add_command(label="About", command=self.program_about, underline=1)
self.master.config(menu=self.menuBar)
self.topFrame = Frame()
self.thread_entry_box = Entry(self.topFrame)
self.thread_entry_box.insert(0, self.DEFAULT_THREAD_TEXT)
self.thread_entry_box.bind('<Return>', lambda event: self.add_thread_GUI())
# Bind needs to send the event to the handler
self.thread_entry_box.pack(side='left', fill='x', expand='True', padx=5)
self.add_thread_btn = Button(self.topFrame)
self.add_thread_btn['text'] = 'Add New Thread'
self.add_thread_btn['command'] = lambda: self.add_thread_GUI()
self.add_thread_btn.pack(side='left', padx=0)
self.topFrame.pack(fill='x')
self.create_thread_frame()
def create_thread_frame(self):
""" Sets up the main thread frame (where the magic happens) """
# Sets up frame
self.thread_list_canvas = Canvas(self.root, borderwidth=0)
self.thread_list_frame = Frame(self.thread_list_canvas)
# Creates scroll bar
self.vsb = Scrollbar(self.root, orient="vertical", command=self.thread_list_canvas.yview)
self.thread_list_canvas.configure(yscrollcommand=self.vsb.set)
self.vsb.pack(side="right", fill="y")
self.hsb = Scrollbar(self.root, orient="horizontal", command=self.thread_list_canvas.xview)
self.thread_list_canvas.configure(xscrollcommand=self.hsb.set)
self.hsb.pack(side="bottom", fill="x")
# Packs frame
self.thread_list_canvas.pack(side="left", fill="both", expand=True)
self.thread_list_canvas.create_window((4, 4), window=self.thread_list_frame, anchor="nw", tags="self.frame")
self.thread_list_frame.bind("<Configure>", self.OnFrameConfigure)
self.create_thread_list_box()
def OnFrameConfigure(self, event):
"""Reset the scroll region to encompass the inner frame"""
self.thread_list_canvas.configure(scrollregion=self.thread_list_canvas.bbox("all"))
# noinspection PyAttributeOutsideInit
def create_thread_list_box(self):
""" Creates the message list box for the create method """
def hover_on(widget):
widget['fg'] = 'dark blue'
# widget['underline'] = True
def hover_off(widget):
widget['fg'] = 'black'
# widget['underline'] = False
for individual_thread in self.MESSAGE_THREADS: # Fetch Message List from model
if individual_thread.is_valid_thread():
self.bg_color = 'green'
else:
self.bg_color = 'red'
self.individual_thread_frame = Frame(self.thread_list_frame,
bg=self.bg_color) # Create frame for each thread
rowToInsertAt = self.MESSAGE_THREADS.index(individual_thread)
self.text_color = 'black'
self.threadText = Label(self.individual_thread_frame, bg=self.bg_color, fg=self.text_color)
self.threadText['text'] = "[ Thread #: " + individual_thread.threadId + " ]"
self.threadText.bind("<Enter>", lambda event, text=self.threadText: hover_on(text))
self.threadText.bind("<Leave>", lambda event, text=self.threadText: hover_off(text))
self.threadText.bind("<Button-1>",
lambda event, thread_in=individual_thread: self.open_in_web_browser(thread_in))
self.threadText.grid(column=0, row=0, sticky='w', padx=0)
#.........这里部分代码省略.........
示例8: Pinball
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import configure [as 别名]
class Pinball(Domain):
"""
The goal of this domain is to maneuver a small ball on a plate into a hole.
The plate may contain obstacles which should be avoided.
**STATE:**
The state is given by a 4-dimensional vector, consisting of position and
velocity of the ball.
**ACTIONS:**
There are 5 actions, standing for slanting the plat in x or y direction
or a horizontal position
of the plate.
**REWARD:**
Slanting the plate costs -4 reward in addition to -1 reward for each timestep.
When the ball reaches the hole, the agent receives 10000 units of reward.
**REFERENCE:**
.. seealso::
G.D. Konidaris and A.G. Barto:
*Skill Discovery in Continuous Reinforcement Learning Domains using Skill Chaining.*
Advances in Neural Information Processing Systems 22, pages 1015-1023, December 2009.
"""
#: default location of config files shipped with rlpy
default_config_dir = os.path.join(
__rlpy_location__,
"Domains",
"PinballConfigs")
def __init__(self, noise=.1, episodeCap=1000,
configuration=os.path.join(default_config_dir, "pinball_simple_single.cfg")):
"""
configuration:
location of the configuration file
episodeCap:
maximum length of an episode
noise:
with probability noise, a uniformly random action is executed
"""
self.NOISE = noise
self.configuration = configuration
self.screen = None
self.episodeCap = episodeCap
self.actions_num = 5
self.actions = [
PinballModel.ACC_X,
PinballModel.DEC_Y,
PinballModel.DEC_X,
PinballModel.ACC_Y,
PinballModel.ACC_NONE]
self.statespace_limits = np.array(
[[0.0, 1.0], [0.0, 1.0], [-2.0, 2.0], [-2.0, 2.0]])
self.continuous_dims = [4]
super(Pinball, self).__init__()
self.environment = PinballModel(
self.configuration,
random_state=self.random_state)
def showDomain(self, a):
if self.screen is None:
master = Tk()
master.title('RLPY Pinball')
self.screen = Canvas(master, width=500.0, height=500.0)
self.screen.configure(background='LightGray')
self.screen.pack()
self.environment_view = PinballView(
self.screen,
500.0,
500.0,
self.environment)
self.environment_view.blit()
self.screen.pack()
self.screen.update()
def step(self, a):
s = self.state
[self.environment.ball.position[0],
self.environment.ball.position[1],
self.environment.ball.xdot,
self.environment.ball.ydot] = s
if self.random_state.random_sample() < self.NOISE:
# Random Move
a = self.random_state.choice(self.possibleActions())
reward = self.environment.take_action(a)
self.environment._check_bounds()
state = np.array(self.environment.get_state())
self.state = state.copy()
return reward, state, self.isTerminal(), self.possibleActions()
def s0(self):
self.environment.ball.position[0], self.environment.ball.position[
1] = self.environment.start_pos
self.environment.ball.xdot, self.environment.ball.ydot = 0.0, 0.0
self.state = np.array(
[self.environment.ball.position[0], self.environment.ball.position[1],
self.environment.ball.xdot, self.environment.ball.ydot])
return self.state, self.isTerminal(), self.possibleActions()
#.........这里部分代码省略.........
示例9: TKinterDisplay
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import configure [as 别名]
class TKinterDisplay(Display):
'''
classdocs
'''
'''
Constructor
'''
def __init__(self, lineThickness=3, maxH=1920, maxW=1080):
master = Tk()
master.maxsize(maxH, maxW)
self.localCanvas = Canvas(master, width=400, height=400)
self.currentlyRenderedWindow = None
self.lineThickness = lineThickness
self.vsb = Scrollbar(master, orient="vertical", command=self.localCanvas.yview)
self.hsb = Scrollbar(master, orient="horizontal", command=self.localCanvas.xview)
self.localCanvas.configure(yscrollcommand=self.vsb.set)
self.localCanvas.configure(xscrollcommand=self.hsb.set)
master.bind("<Configure>", self.__eventOnFrameConfigure)
self.hsb.pack(side="bottom", fill="x")
self.vsb.pack(side="right", fill="y")
self.localCanvas.pack()
self.__sampleDraw()
''''''
@abstractmethod
def drawSquare(self, xywhTuple, tags=None, colour=None, content=None):
x2 = xywhTuple[0] + xywhTuple[2]
y2 = xywhTuple[1] + xywhTuple[3]
square = self.localCanvas.create_rectangle(xywhTuple[0], xywhTuple[1], x2, y2, width=self.lineThickness, tags=tags, fill=colour, activeoutline="white")
def handler(event, self=self, content=content):
return self.__eventOnClick(event, content)
self.localCanvas.tag_bind(square, "<ButtonRelease-1>", handler)
return square
@abstractmethod
def drawCircle(self, xywhTuple, tags=None , colour=None, content=None):
x2 = xywhTuple[0] + xywhTuple[2]
y2 = xywhTuple[1] + xywhTuple[3]
circle = self.localCanvas.create_oval(xywhTuple[0], xywhTuple[1], x2, y2, width=self.lineThickness, tags=tags, fill=colour, activeoutline="white")
def handler(event, self=self, content=content):
return self.__eventOnClick(event, content)
self.localCanvas.tag_bind(circle, "<ButtonRelease-1>", handler)
return circle
@abstractmethod
def connectIdWithLine(self, id1, id2, tags=None, colour=None):
# Gets the coordinates of id1 and then calulates centre point
id1tuple = self.__getCoords(id1)
x1 = id1tuple[0] + ((id1tuple[2] - id1tuple[0]) / 2)
y1 = id1tuple[1] + ((id1tuple[3] - id1tuple[1]) / 2)
# Gets the coordinates of id2 and then calulates centre point
id2tuple = self.__getCoords(id2)
x2 = id2tuple[0] + ((id2tuple[2] - id2tuple[0]) / 2)
y2 = id2tuple[1] + ((id2tuple[3] - id2tuple[1]) / 2)
# Calculates, using trig, the angle of the line at shape id1. This gives the radius of the ellipse
opposite = y1 - y2
adjacent = x1 - x2
x1angle = 0
x2angle = 0
hyp = 0
if adjacent != 0 and opposite != 0:
hyp = math.sqrt(math.pow(opposite, 2) + math.pow(adjacent, 2))
x1angle = math.tan(opposite / adjacent)
x2angle = math.tan(adjacent / opposite)
else:
if opposite == 0:
hyp = adjacent
else:
hyp = opposite
x1angle = math.radians(90)
x2angle = math.radians(270)
a1 = (id1tuple[2] - id1tuple[0]) / 2
b1 = (id1tuple[3] - id1tuple[1]) / 2
a2 = (id2tuple[2] - id2tuple[0]) / 2
b2 = (id2tuple[3] - id2tuple[1]) / 2
r1 = a1 * b1 / (math.sqrt(((a1 * a1) * (math.pow(math.sin(x1angle), 2))) + ((b1 * b1) * math.pow(math.cos(x1angle), 2))))
r2 = a2 * b2 / (math.sqrt(((a2 * a2) * (math.pow(math.sin(x2angle), 2))) + ((b2 * b2) * math.pow(math.cos(x2angle), 2))))
x1 = x1 + ((r1 / hyp) * (x2 - x1))
y1 = y1 + ((r1 / hyp) * (y2 - y1))
#x2 = x2 + ((r2 / hyp) * (x1 - x2))
#y2 = y2 - ((r2 / hyp) * (y1 - y2))
return self.__drawLine(x1, y1, x2, y2, tags, colour)
#.........这里部分代码省略.........
示例10: RadiobuttonEntry
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import configure [as 别名]
class RadiobuttonEntry(ttk.Frame):
"""State entry for the entire conflict. A set of RadioButtonSeries."""
def __init__(self, master, conflict):
"""State entry widget for the entire conflict."""
ttk.Frame.__init__(self, master)
self.conflict = conflict
self.rbeCanvas = Canvas(self)
self.rdBtnFrame = ttk.Frame(self.rbeCanvas)
self.scrollY = ttk.Scrollbar(self, orient=VERTICAL,
command=self.rbeCanvas.yview)
self.rbeCanvas.grid(column=0, row=0, columnspan=2, sticky=NSEW)
self.scrollY.grid(column=2, row=0, sticky=NSEW)
self.rbeCanvas.configure(yscrollcommand=self.scrollY.set)
self.canvWindow = self.rbeCanvas.create_window((0, 0),
window=self.rdBtnFrame,
anchor='nw')
self.rowconfigure(0, weight=1)
self.entryText = StringVar(value='')
vcmd = self.register(self.onValidate)
self.entryBx = ttk.Entry(self, textvariable=self.entryText,
validate="key",
validatecommand=(vcmd, '%S', '%P'))
self.entryBx.grid(column=0, row=1, sticky=NSEW)
self.entryBx.bind('<Return>', self.generateAdd)
self.warnText = StringVar(value='')
self.warnLab = ttk.Label(self, textvariable=self.warnText, width=18)
self.warnLab.grid(column=1, row=1, sticky=NSEW)
self.codeText = StringVar(value='')
vcmd2 = self.register(self.onValidate2)
self.codeBx = ttk.Entry(self, textvariable=self.codeText,
validate="key",
validatecommand=(vcmd2, '%S', '%P'))
self.codeBx.grid(column=0, row=2, sticky=NSEW)
self.codeBx.bind('<Return>', self.generateAdd)
self.warnText2 = StringVar(value='')
self.warnLab2 = ttk.Label(self, textvariable=self.warnText2)
self.warnLab2.grid(column=1, row=2, sticky=NSEW)
self.addBtn = ttk.Button(self, text='Add as Prefered State',
command=self.generateAdd)
self.stageBtn = ttk.Button(self, text='Add to Staging',
command=self.generateStage)
self.addBtn.grid(column=0, row=4, columnspan=2, sticky=NSEW)
self.stageBtn.grid(column=0, row=5, columnspan=2, sticky=NSEW)
self.isDisabled = False
self.columnconfigure(0, weight=1)
self.reloadOpts()
self.regexValidChars = re.compile(r'^[-\d, fi]*$')
self.regexStatesIf = re.compile(r'^ *(-)?(\d+) *iff? *(-)?(\d+) *$')
self.regexStates = re.compile(r' *(-)?(\d+) *')
self.hasValidIf = False
def resize(self, event=None):
"""Adjust the canvas widget if the window is resized."""
self.rbeCanvas.configure(scrollregion=self.rbeCanvas.bbox("all"))
self.rbeCanvas["width"] = self.rbeCanvas.bbox("all")[2]
def generateAdd(self, event=None):
"""Generate event if a preference is added."""
self.event_generate('<<AddPref>>')
def generateStage(self, event=None):
"""Generate event if a preference is staged."""
self.event_generate('<<StagePref>>')
def reloadOpts(self):
"""Reload options for all decision makers."""
self.rbeCanvas.delete(self.canvWindow)
self.rdBtnFrame.destroy()
self.rdBtnFrame = ttk.Frame(self.rbeCanvas)
self.canvWindow = self.rbeCanvas.create_window((0, 0),
window=self.rdBtnFrame,
anchor='nw')
self.rdBtnFrame.bind('<<RdBtnChg>>', self.rdBtnChgCmd)
self.rdBtnFrame.bind("<Configure>", self.resize)
self.rdBtnSrs = []
self.stringVarList = []
for x, dm in enumerate(self.conflict.decisionMakers):
a = RadiobuttonSeries(self.rdBtnFrame, dm)
self.rdBtnSrs.append(a)
a.setOpts(dm.options)
#.........这里部分代码省略.........
示例11: RunScreen
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import configure [as 别名]
class RunScreen(Frame):
def __init__(self, master, valves):
Frame.__init__(self, master, bg='sky blue', width=950, height=750)
self.master = master
self.valves = valves
self.threads = []
self.canvas = Canvas(self, height=750, width=950, bg='sky blue')
self.frame = Frame(self.canvas, bg='sky blue')
self.scrollbar = Scrollbar(self, orient='vertical', command=self.canvas.yview)
self.scrollbar.configure(activebackground='DarkRed', background='red', width=40)
self.canvas.configure(yscrollcommand=self.scrollbar.set, scrollregion=[0, 0, 1366, 1300])
self.scrollbar.pack(side='right', fill='y')
self.canvas.pack(side='left')
self.canvas.create_window((0, 0), window=self.frame, anchor='nw')
self.frame.config(bg='sky blue')
self.valve_num = [Label(self.frame, text='1'),
Label(self.frame, text='2'),
Label(self.frame, text='3'),
Label(self.frame, text='4'),
Label(self.frame, text='5'),
Label(self.frame, text='6'),
Label(self.frame, text='7'),
Label(self.frame, text='8')]
row = 0
for each in self.valve_num:
each.grid(row=row, column=0)
each.config(width=4, font=('Lucida Console', 30), bg='sky blue', fg='RoyalBlue4')
row += 2
self.valve_name = [Label(self.frame, textvariable=valves[0].get_name()),
Label(self.frame, textvariable=valves[1].get_name()),
Label(self.frame, textvariable=valves[2].get_name()),
Label(self.frame, textvariable=valves[3].get_name()),
Label(self.frame, textvariable=valves[4].get_name()),
Label(self.frame, textvariable=valves[5].get_name()),
Label(self.frame, textvariable=valves[6].get_name()),
Label(self.frame, textvariable=valves[7].get_name())]
row = 0
for each in self.valve_name:
each.grid(row=row, column=2)
each.config(width=15, font=('Lucida Console', 30), bg='sky blue', fg='RoyalBlue4')
row += 2
valve = 0
self.valve_activity = []
self.on_image = PhotoImage(file="img/yes.png").subsample(x=6, y=6)
self.off_image = PhotoImage(file="img/no.png").subsample(x=6, y=6)
for each in self.valves:
if each.get_setting() is 'INACTIVE':
self.valve_activity.append(Button(self.frame, image=self.off_image, text='OFF', command=lambda: self.activate(valve)))
else:
self.valve_activity.append(Button(self.frame, image=self.on_image, text='ON', command=lambda: self.activate(valve)))
valve += 1
row = 0
for each in self.valve_activity:
each.grid(row=row, column=1)
each.config(bg='SkyBlue4', activebackground='midnight blue')
each.config()
row += 2
self.valve_action_a = [Label(self.frame, textvariable=valves[0].get_action_a()),
Label(self.frame, textvariable=valves[1].get_action_a()),
Label(self.frame, textvariable=valves[2].get_action_a()),
Label(self.frame, textvariable=valves[3].get_action_a()),
Label(self.frame, textvariable=valves[4].get_action_a()),
Label(self.frame, textvariable=valves[5].get_action_a()),
Label(self.frame, textvariable=valves[6].get_action_a()),
Label(self.frame, textvariable=valves[7].get_action_a())]
row = 0
for each in self.valve_action_a:
each.grid(row=row, column=3)
each.config(width=10, font=('Lucida Console', 30), bg='sky blue', fg='RoyalBlue4', anchor='w')
row += 2
self.valve_action_b = [Label(self.frame, textvariable=valves[0].get_action_b()),
Label(self.frame, textvariable=valves[1].get_action_b()),
Label(self.frame, textvariable=valves[2].get_action_b()),
Label(self.frame, textvariable=valves[3].get_action_b()),
Label(self.frame, textvariable=valves[4].get_action_b()),
Label(self.frame, textvariable=valves[5].get_action_b()),
Label(self.frame, textvariable=valves[6].get_action_b()),
Label(self.frame, textvariable=valves[7].get_action_b())]
row = 1
for each in self.valve_action_b:
each.grid(row=row, column=3)
each.config(width=10, font=('Lucida Console', 30), bg='sky blue', fg='RoyalBlue4', anchor='w')
row += 2
self.lightsA = [LED(self.frame, 30, 'green1', 'green', 'dark green', 'Dark Green', False),
LED(self.frame, 30, 'green1', 'green', 'dark green', 'Dark Green', False),
LED(self.frame, 30, 'green1', 'green', 'dark green', 'Dark Green', False),
#.........这里部分代码省略.........
示例12: TkLEDTableMixin
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import configure [as 别名]
class TkLEDTableMixin(object):
BACKGROUND_COLOR = "black"
BORDER_COLOR = "gray"
PIXEL_ORDER_COLOR = "white"
PIXEL_WIDTH = 30
PIXEL_HEIGHT = 30
PIXEL_BORDER = 1
def __init__(self, *args, **kw):
self._canvas = Canvas(self, width = 0, height = 0)
self._canvas.pack()
self._pixels = []
self._saved_pixels = []
self._pixel_order = []
self._pixel_width = self.PIXEL_WIDTH
self._pixel_height = self.PIXEL_HEIGHT
self._pixel_border = self.PIXEL_BORDER
self._height = self._width = 0
# initial configuration
@property
def width(self):
return self._width
@width.setter
def width(self, value):
self.dimensions = value, self.height
@property
def height(self):
return self._height
@height.setter
def height(self, value):
self.dimensions = self.width, value
@property
def dimensions(self):
return self._width, self._height
@dimensions.setter
def dimensions(self, value):
width, height = value
self._remove_all_pixels()
self._width, self._height = width, height
self._create_pixels()
# utility methods
def _create_pixels(self):
assert not self._pixels
for y in range(self.height):
pixels = []
self._pixels.append(pixels)
for x in range(self.width):
pixel = self._canvas.create_rectangle(0,0,1,1)
pixels.append(pixel)
self._update_configuration()
for y, row in enumerate(self._saved_pixels[:self.height]):
for x, color in enumerate(row[:self.width]):
self.set_pixel_color(x, y, color)
def _remove_all_pixels(self):
self._saved_pixels = [[self.get_pixel_color(x, y) for x in range(self.width)] for y in range(self.height)]
for pixel in self._all_pixels:
self._canvas.delete(pixel)
self._pixels = []
self._remove_pixel_order()
def _remove_pixel_order(self):
for line in self._pixel_order:
self._canvas.delete(line)
self._pixel_order = []
@property
def _all_pixels(self):
return chain.from_iterable(self._pixels)
def _update_configuration(self):
for y, row in enumerate(self._pixels):
for x, pixel in enumerate(row):
x_cor = x * self.pixel_width
y_cor = y * self.pixel_height
self._canvas.coords(pixel, x_cor, y_cor,
x_cor + self.pixel_width,
y_cor + self.pixel_height)
self._canvas.itemconfigure(pixel, outline = self.BORDER_COLOR,
fill = self.BACKGROUND_COLOR,
width = self.pixel_border)
self._canvas.configure(width = self.width * self.pixel_width,
height = self.height * self.pixel_height)
# pixel configuration
@property
def pixel_width(self):
return self._pixel_width
@pixel_width.setter
#.........这里部分代码省略.........