本文整理汇总了Python中tkinter.Canvas.create_window方法的典型用法代码示例。如果您正苦于以下问题:Python Canvas.create_window方法的具体用法?Python Canvas.create_window怎么用?Python Canvas.create_window使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tkinter.Canvas
的用法示例。
在下文中一共展示了Canvas.create_window方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Main
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_window [as 别名]
class Main(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.info = {}
self.window = None
self.size = (640, 480)
self.fields = []
self.init_ui()
def init_ui(self):
self.parent.title("Node Writer")
self.style = Style()
self.style.theme_use("alt")
self.pack(fill="both", expand=True)
menubar = Menu(self.parent)
self.parent.config(menu=menubar)
menubar.add_command(label="New", command=self.onNew)
menubar.add_command(label="Show Info", command=self.get_info)
menubar.add_command(label="Exit", command=self.quit)
self.canvas = Canvas(self, background="white", width=self.size[0], height=self.size[1])
self.canvas.pack(fill="both", expand=1)
self.canvas.bind("<Motion>", self.move_boxes)
def move_boxes(self, event):
print(event.x, event.y)
"""
x, y = (event.x-1, event.y-1)
x1, y1, x2, y2 = self.canvas.bbox("test")
if x > x1 and y > y1 and x < x2 and y < y2:
print("Hit")
else:
print("Missed")
"""
def onNew(self):
new = Node(self, "Node_entry")
label = new.insert_entry_field("Labels")
label2 = new.insert_entry_field("Labels2")
text = new.insert_text_field("Text")
new.ok_cancel_buttons()
def get_info(self):
x, y = (self.size[0]/2, self.size[1]/2)
for i in self.info:
label_frame= LabelFrame(self, text="name")
label_frame.pack(fill="y")
for entry in self.info[i]["Entry"]:
frame = Frame(label_frame)
frame.pack(fill="x")
label = Label(label_frame, text=self.info[i]["Entry"][entry], width=6)
label.pack(side="left", anchor="n", padx=5, pady=5)
for text in self.info[i]["Text"]:
frame = Frame(label_frame)
frame.pack(fill="x")
label = Label(label_frame, text=self.info[i]["Text"][text], width=6)
label.pack(side="left", anchor="n", padx=5, pady=5)
window = self.canvas.create_window(x, y, window=label_frame, tag="test")
示例2: __init__
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_window [as 别名]
def __init__(self, parent, *args, **kw):
Frame.__init__(self, parent, *args, **kw)
# create a canvas object and a vertical scrollbar for scrolling it
vscrollbar = Scrollbar(self, orient=VERTICAL)
vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE)
canvas = Canvas(self, bd=0, highlightthickness=0,
yscrollcommand=vscrollbar.set)
self._canvas = canvas
canvas.pack(side=LEFT, fill=BOTH, expand=TRUE)
vscrollbar.config(command=canvas.yview)
# reset the view
canvas.xview_moveto(0)
canvas.yview_moveto(0)
# create a frame inside the canvas which will be scrolled with it
self.interior = interior = Frame(canvas)
interior_id = canvas.create_window(0, 0, window=interior,
anchor=NW)
# track changes to the canvas and frame width and sync them,
# also updating the scrollbar
def _configure_interior(event):
# update the scrollbars to match the size of the inner frame
size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
canvas.config(scrollregion="0 0 %s %s" % size)
if interior.winfo_reqwidth() != canvas.winfo_width():
# update the canvas's width to fit the inner frame
canvas.config(width=interior.winfo_reqwidth())
if interior.winfo_reqheight() != canvas.winfo_height():
# update the canvas's height to fit the inner frame
canvas.config(height=interior.winfo_reqheight())
interior.bind('<Configure>', _configure_interior)
def _configure_canvas(event):
"""
This function is called when the canvas is configured, that is on resize and so on,
"""
if interior.winfo_reqwidth() != canvas.winfo_width():
# update the inner frame's width to fill the canvas
canvas.itemconfigure(interior_id, width=canvas.winfo_width())
if interior.winfo_reqheight() != canvas.winfo_height():
# update the inner frame's height to fill the canvas
canvas.itemconfigure(interior_id, height=canvas.winfo_height())
canvas.bind('<Configure>', _configure_canvas)
return
示例3: GPIOSim
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_window [as 别名]
#.........这里部分代码省略.........
# Method that updates the current status, getting info from the file
# Shall be called on receivment of SIGIUSR (sent by the GPIO class)
def updateUI(self):
self.canvas.delete("all")
c = RawConfigParser()
c.read(self.WORK_FILE)
x = self.START_X
y = self.START_Y
for i in range(0,40):
state = c.getint("pin"+str(i),"state")
value = c.getint("pin"+str(i),"value")
ident = 2*state+value
self.currState[i] = state
self.currValue[i] = value
e_x = x + self.PIN_SIZE
e_y = y + self.PIN_SIZE
self.canvas.create_oval(x, y, e_x, e_y, outline="black", fill=self.PIN_COLORS[ident], width=2, tags='pin'+str(i))
self.canvas.tag_bind('pin'+str(i),'<Button>', self.click_cb(i) )
if i%2==0: #LEFT COLUMN GPIOS
self.canvas.create_window(x-70, y+10, window=Label(self.canvas, text=self.GPIO_NAMES[i], fg=self.TEXT_COLOR, bg= self.BG_COLOR))
if ident==2: #IN_LOW
self.canvas.create_window(x - 20, y+8, window=Label(self.canvas, image=self.phInLeft, bd=0))
#freccia e cliccabile(?)
elif ident==3: #IN_HIGH
self.canvas.create_window(x - 20, y+8, window=Label(self.canvas, image=self.phInLeft, bd=0))
#freccia e cliccabile(?)
elif state==self.STATE_GPIO_OUT: #OUT
self.canvas.create_window(x - 20, y+8, window=Label(self.canvas, image=self.phOutLeft, bd=0))
x = e_x + self.PIN_DISTANCE
else: #RIGHT COLUMN GPIOS
self.canvas.create_window(e_x + 70, y+10, window=Label(self.canvas, text=self.GPIO_NAMES[i], fg=self.TEXT_COLOR, bg= self.BG_COLOR))
if ident==2: #IN_LOW
self.canvas.create_window(e_x + 22, y+8, window=Label(self.canvas, image=self.phInRight, bd=0))
#freccia e cliccabile(?)
elif ident==3: #IN_HIGH
self.canvas.create_window(e_x + 22, y+8, window=Label(self.canvas, image=self.phInRight, bd=0))
#freccia e cliccabile(?)
elif state==self.STATE_GPIO_OUT: #OUT
self.canvas.create_window(e_x + 22, y+8, window=Label(self.canvas, image=self.phOutRight, bd=0))
y = e_y + self.PIN_DISTANCE
x = self.START_X
示例4: Visual
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_window [as 别名]
class Visual(object):
def __init__(self, width=800, height=600):
root = Tk()
self.root = root
self.margin = 0.12*height
self.width, self.height = width, height - self.margin
self.cx, self.cy = width/2, (height - self.margin)/2
self.toolbar = \
Canvas(self.root, width=self.width, height=self.margin)
self.toolbar.pack()
self.canvas = Canvas(root, width=width, height=height - self.margin)
self.canvas.pack()
self.init_animation()
root.bind("<Button-1>", lambda e: self.mouse_event(e))
root.bind("<Key>", lambda e: self.key_event(e))
root.mainloop()
def draw_users(self):
"""Draw all users"""
for user in self.users:
user.draw()
def draw_connections(self):
"""Draw all of user's connections"""
for user in self.users:
user.draw_students()
def draw_start_screen(self):
"""Start screen text"""
self.canvas.delete(ALL)
cx, cy = self.width/2, self.height/2
font = ("Impact", "128")
self.canvas.create_text(cx, 0.8*cy, text="INFECTION", font=font)
font = ("Impact", 32)
self.canvas.create_text(cx, 1.5*cy, text="Press s to Begin", font=font)
def draw_setup_screen(self):
"""User setup screen"""
self.canvas.delete(ALL)
cx, cy = self.width/2, self.height/2
text = "Number of Users (1-{})".format(self.max_users)
font = ("Impact", 24)
self.canvas.create_text(cx, 0.4*cy, text=text, font=font)
self.num_users_entry = Entry(self.canvas, justify=CENTER)
self.canvas.create_window(cx, 0.5*cy, window=self.num_users_entry)
self.num_users_entry.insert(0, str(self.default_users))
text = "Number of Coaches"
self.canvas.create_text(cx, 0.6*cy, text=text, font=font)
self.num_coaches_entry = Entry(self.canvas, justify=CENTER)
self.canvas.create_window(cx, 0.7*cy, window=self.num_coaches_entry)
self.num_coaches_entry.insert(0, str(self.default_coaches))
text = "Max Number of Students"
self.canvas.create_text(cx, 0.8*cy, text=text, font=font)
self.num_students_entry = Entry(self.canvas, justify=CENTER)
self.canvas.create_window(cx, 0.9*cy, window=self.num_students_entry)
self.num_students_entry.insert(0, str(self.default_students))
self.button = Button(cx, 1.5*cy, 0.3*cx, 0.2*cy, "Begin")
self.button.draw(self.canvas)
def draw_toolbar(self):
"""Toolbar for main animation"""
self.toolbar.create_text(self.cx, 0.1*self.cy, text="INFECTION",
font=("Impact", 32))
self.toolbar.create_text(self.cx*0.05, 0.1*self.cy,
text="Total Infection: Click User",
font=("Impact", 20), anchor="w")
self.toolbar.create_text(self.cx*1.8, 0.1*self.cy,
text="Limited Infection",
font=("Impact", 20), anchor="e")
self.limited_entry = Entry(self.toolbar, justify=CENTER, width=3)
self.toolbar.create_window(self.cx*1.85, 0.1*self.cy,
window=self.limited_entry)
self.limited_entry.insert(0, str(self.default_users//2))
cx, cy = self.cx*1.95, self.margin*0.35
r = self.margin/5
self.limited_button = (cx, cy, r)
self.toolbar.create_oval((cx-r, cy-r, cx+r, cy+r), width=2, fill="RED")
self.toolbar.create_text(cx, cy, text="X", font=("Courier Bold", 30))
side = self.width/self.versions
self.side = side
y = 50
self.gradient = (y, y+side)
for col in range(int(self.versions)):
fill = self.get_fill(col)
width = 2 if col == self.version else 0
self.toolbar.create_rectangle(col*side, y, (col+1)*side, y+side,
fill=fill, width=width)
self.select_version()
def redraw_all(self):
"""Refresh frame for infection animation"""
self.canvas.delete(ALL)
# Draw connections first so circles get drawn on top of lines
self.draw_connections()
self.draw_users()
def init_users(self):
#.........这里部分代码省略.........
示例5: RadiobuttonEntry
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_window [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 '
#.........这里部分代码省略.........
示例6: Edit
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_window [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])]
#.........这里部分代码省略.........
示例7: Preferences
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_window [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=''),
#.........这里部分代码省略.........
示例8: mainGUI
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_window [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)
#.........这里部分代码省略.........
示例9: GUI
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_window [as 别名]
class GUI():
"""
Method gets a Tk instance (master) and a model instance implemented with nengo.
It then creates a GUI with the polts that where specified in create_plot(...).
"""
def __init__(self, master, model):
self.f = 0
master.rowconfigure(0, weight=1)
master.columnconfigure(0, weight=1)
self.frame = tk.Frame(master)
self.frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)
self.frame.grid(sticky=NSEW)
self.frame.rowconfigure(0, weight=1)
self.frame.columnconfigure(0, weight=1)
self.scroll_canvas = Canvas(self.frame)
self.scroll_canvas.grid(row=0, column=0, sticky=NSEW)
xScrollbar = Scrollbar(self.frame, orient=HORIZONTAL)
yScrollbar = Scrollbar(self.frame)
xScrollbar.grid(row=1, column=0, sticky=EW)
yScrollbar.grid(row=0, column=1, sticky=NS)
self.scroll_canvas.config(xscrollcommand=xScrollbar.set)
xScrollbar.config(command=self.scroll_canvas.xview)
self.scroll_canvas.config(yscrollcommand=yScrollbar.set)
yScrollbar.config(command=self.scroll_canvas.yview)
self.create_plot(model)
self.figure_canvas = FigureCanvasTkAgg(self.f, master=self.scroll_canvas)
self.canvas = self.figure_canvas.get_tk_widget()
self.canvas.pack(side=tk.TOP, fill=tk.BOTH, padx=5, pady=5, expand=1)
self.scroll_canvas.create_window(0, 0, window=self.canvas)
self.scroll_canvas.config(scrollregion=self.scroll_canvas.bbox(ALL))
self.figure_canvas.show()
self.toolbar = NavigationToolbar2TkAgg(self.figure_canvas, self.scroll_canvas)
self.toolbar.pack()
self.toolbar.update()
"""
Adds the specified plots to the figure displayed in the GUI. It gets a model instance implemented with nengo
"""
def create_plot(self, model):
self.f = Figure(figsize=(16, 9), dpi=80)
"""
Example plot which plots the integrators back connection, its input, its real value and the real robot goal angle
"""
self.ax00 = self.f.add_axes((.2, .2, .6, .6), axisbg=(.75, .75, .75), frameon=True)
self.ax00.plot(model.sim.trange(), model.sim.data[model.integrator_probe], label = 'Integrator')
self.ax00.plot(model.sim.trange(), model.sim.data[model.integrator_connection_probe], label = 'Con')
self.ax00.plot(model.sim.trange(), model.sim.data[model.integrator_self_connection_probe], label = 'Self Con')
self.ax00.plot(model.sim.trange(), model.sim.data[model.robot_goal_neuron_probe][:, 2], label = 'Real')
self.ax00.legend()
示例10: simpleGui
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_window [as 别名]
#.........这里部分代码省略.........
rowLine=rowLine+1
self.grid_rowconfigure(rowLine, weight=1)
self.textBox = tkst.ScrolledText(self, width=20, height=10)
self.textBox.grid(column=0, row=rowLine, columnspan=3, sticky='NWES')
self.textBox.config(state=DISABLED)
self.canvas= Canvas(master=self,width=150)
self.vscroll = Scrollbar(self)
self.vscroll.config(command=self.canvas.yview)
self.canvas.config(yscrollcommand=self.vscroll.set)
self.canvas.grid( row=rowLine, column=3, sticky='NES')
self.vscroll.grid(padx=1, pady=1, row=rowLine, column=4, sticky='NEWS')
rowLine=rowLine+1
buttonClearHighlight = tkinter.Button(self, text="Clear highlight", width=20, command=self.removeHighlightsBtn)
buttonClearHighlight.grid(column=0, row=rowLine, sticky="WS")
buttonDeleteWords = tkinter.Button(self, text="Delete words", width=20, command=self.resetAll)
buttonDeleteWords.grid(column=3, row=rowLine, sticky="ES")
self.grid_columnconfigure(0, weight=1)
self.grid_columnconfigure(1, weight=1)
def setPath(self):
try:
open(self.entryPath.get())
except:
return
self.path=self.entryPath.get()
self.textBox.config(state=NORMAL)
self.textBox.insert(tkinter.INSERT, open(self.path).read())
self.textBox.config(state=DISABLED)
def removeHighlights(self):
for wordFrame in self.wordFrames:
wordFrame.removeHighLight()
def removeHighlightsBtn(self, entry=""):
for wordFrame in self.wordFrames:
wordFrame.removeHighLight()
self.update_idletasks()
def resetAll(self, entry=""):
self.removeHighlights()
self.algo.resetTree()
self.lastCanvasIndex=0;
self.wordFrames=[]
self.canvas.delete("all")
self.update_idletasks()
def addWords(self, event=""):
if(self.path==""):
return
if(self.entry.get().strip()==""):
self.entry.delete(0,len(self.entry.get()))
return
self.resetAll()
for word in self.entry.get().split(" "):
if word.lower() not in self.algo.foundWords.keys() and word != "" and word!=None:
self.algo.addWord(word)
self.addToCanvas(word)
self.entry.delete(0,len(self.entry.get()))
self.algo.addFails()
self.algo.readFile(self.path)
self.updateCanvasPositions();
def updateCanvasPositions(self):
for word in self.wordFrames:
self.wordFrames[self.wordFrames.index(word)].updatePositions(self.algo.foundWords[word.getWord().lower()])
self.wordFrames[self.wordFrames.index(word)].addTags()
def addToCanvas(self, word):
frame=wordFrame(self.canvas, self, word, self.algo.foundWords[word.lower()])
self.wordFrames.append(frame)
self.canvas.create_window(0, 50+self.lastCanvasIndex*50,anchor="w", window=frame, height=50)
self.canvas.config(scrollregion=(0,0,70+self.lastCanvasIndex*50,70+self.lastCanvasIndex*50))
self.canvas.update_idletasks()
self.update_idletasks()
self.lastCanvasIndex=self.lastCanvasIndex+1;
示例11: RadiobuttonEntry
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_window [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)
#.........这里部分代码省略.........
示例12: RunScreen
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_window [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),
#.........这里部分代码省略.........
示例13: __createWindowOnId
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_window [as 别名]
def __createWindowOnId(self, itemId, content):
if self.currentlyRenderedWindow != None:
self.currentlyRenderedWindow()
# self.__remove(self.currentlyRenderedWindow)
idtuple = self.localCanvas.coords(itemId)
if idtuple:
x = idtuple[0]
y = idtuple[1]
frm = Frame(self.localCanvas)
frm.grid(row=0, column=0)
canv = Canvas(frm)
vscroll = Scrollbar(frm, orient="vertical", command=canv.yview)
vscroll.grid(row=0, column=1, sticky=N + S)
canv.grid(row=0, column=0)
canv["yscrollcommand"] = vscroll.set
aframe = Frame(canv)
aframe.grid(row=0, column=0)
Label(aframe, text=content, anchor="center", background="#CCFFCC", borderwidth=6, relief="ridge", justify="left").grid(row=1, column=0)
canvWindow = canv.create_window(x, y, window=aframe)
canv.coords(canvWindow, x, y)
self.localCanvas.update_idletasks()
canv["scrollregion"] = canv.bbox("all")
def destroyAll():
self.__remove(canvWindow)
canv.destroy()
aframe.destroy()
vscroll.destroy()
frm.destroy()
self.currentlyRenderedWindow = destroyAll
Button(frm, text="Close", command=lambda : destroyAll()).grid(row=2, column=0)