本文整理汇总了Python中tkinter.Canvas.config方法的典型用法代码示例。如果您正苦于以下问题:Python Canvas.config方法的具体用法?Python Canvas.config怎么用?Python Canvas.config使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tkinter.Canvas
的用法示例。
在下文中一共展示了Canvas.config方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: draw_automata
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import config [as 别名]
def draw_automata(turing_machine=None):
w = len(turing_machine.states)
h = len(turing_machine.rules)
root = Tk()
frame = Frame(root, width=800, height=600)
frame.grid(row=0, column=0)
canvas = Canvas(frame, bg='#FFFFFF', width=800, height=600,
scrollregion=(0, -h * 15, w * 100, h * 15*3))
hbar = Scrollbar(frame, orient=HORIZONTAL)
hbar.pack(side=BOTTOM, fill=X)
hbar.config(command=canvas.xview)
vbar = Scrollbar(frame, orient=VERTICAL)
vbar.pack(side=RIGHT, fill=Y)
vbar.config(command=canvas.yview)
canvas.config(width=800, height=600)
canvas.config(xscrollcommand=hbar.set, yscrollcommand=vbar.set)
canvas.pack(side=LEFT, expand=True, fill=BOTH)
for position, state in enumerate(turing_machine.states):
state_position[state] = position
loop_occurrences[position] = 0
canvas_id = canvas.create_text(10 + 80 * position, 400, anchor="nw")
canvas.itemconfig(canvas_id, text="state-")
canvas.insert(canvas_id, 12, "%d" % state)
counter = 1
for rule in turing_machine.rules:
counter = draw_arrow(state_position[rule.current_state],
state_position[rule.next_state],
canvas, counter, rule)
root.mainloop()
示例2: TkWindow
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import config [as 别名]
class TkWindow(tkinter.Tk):
def __init__(self,parent):
tkinter.Tk.__init__(self,parent)
self.parent = parent
self.initialize()
def initialize(self):
self.grid()
buttonFile = tkinter.Button(self,text=u"Get file",command=self.getFile)
buttonFile.grid(column=0,row=1,sticky='EW',padx=10,pady=10)
buttonCrypto = tkinter.Button(self,text=u"Crypto",command=self.crypto)
buttonCrypto.grid(column=0,row=3,sticky='EW',padx=10,pady=10)
#labelHeader = Tkinter.Label(self,text=u"Database file:",anchor="w")
#labelHeader.grid(column=0,row=0,columnspan=3,padx=10,pady=10,sticky='EW')
self.labelVariable = tkinter.StringVar()
labelFileName = tkinter.Label(self,textvariable=self.labelVariable,anchor="w",fg="black",bg="white")
labelFileName.grid(column=1,row=1,columnspan=2,sticky='EW',padx=10,pady=10)
self.canvas = Canvas(self,width=400, height=400,bd=0,bg="blue")
self.canvas.grid(row = 2,column = 0,columnspan=2,sticky='EW',padx=10,pady=10)
#self.photo = ImageTk.PhotoImage(file = "/home/paulina/obrazki/obrazek.jpg")
#self.canvas.create_image(0,0, image = self.photo)
def getFile(self):
self.fileName = filedialog.askopenfilename(initialdir = "/home/paulina/obrazki",title = "choose your file",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))
self.labelVariable.set(self.fileName)
self.photo = Image.open(self.fileName)
(imageSizeWidth, imageSizeHeight) = self.photo.size
print(imageSizeWidth, imageSizeHeight)
newImageSizeHeight = 400
n = imageSizeHeight/newImageSizeHeight
print(n)
newImageSizeWidth = int(imageSizeWidth/n)
print(newImageSizeWidth, newImageSizeHeight)
self.canvas.config(width=newImageSizeWidth,height=newImageSizeHeight)
self.photo = self.photo.resize((newImageSizeWidth, newImageSizeHeight), Image.ANTIALIAS)
self.photo = ImageTk.PhotoImage(self.photo)
self.canvas.create_image(int(newImageSizeWidth/2), int(newImageSizeHeight/2), image = self.photo)
def crypto(self):
obj = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
message = "The answer is no"
ciphertext = obj.encrypt(message)
print(ciphertext)
obj2 = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
messagedec = obj2.decrypt(ciphertext)
print(messagedec)
示例3: progress
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import config [as 别名]
def progress( self ):
o=os.popen("cd {0} && snakemake --dryrun --rerun-incomplete > {0}/Reports/checkpoint".format(self.workpath.get()))
o.close()
F=open("{0}/Reports/checkpoint".format(self.workpath.get()),"r").read()
rules2={}
rules=re.findall(r'rule .+:',F)
for i in rules:
i=re.sub("rule ","",i)
i=re.sub(":","",i)
rules2[i]=0
F=open("{0}/Reports/{1}.dot".format(self.workpath.get(), self.Pipeline.get() ),"r").read()
for i in rules2.keys():
F=re.sub(r'('+i+')(\".+?)\".+?\"',r'\1_pending\2"0.0 0.0 0.0"',F)
# F=re.sub(i,"",F)
G=open("{0}/Reports/{1}-{2}.dot".format(self.workpath.get(),self.Pipeline.get(),"progress"),"w")
G.write(F)
G.close()
o=os.popen("cd {0}/Reports && dot -Tpng -o {0}/Reports/{1}-progress.png {0}/Reports/{1}-progress.dot;convert {0}/Reports/{1}-progress.png {0}/Reports/{1}-progress.gif".format(self.workpath.get(),self.Pipeline.get()))
# tkinter.messagebox.showerror("o",o)
PL=self.Pipeline.get() #pipelineget()
gf=Toplevel()
gf.title("CCBR Pipeliner: {0} Progress Graph".format(PL))
cgf = Canvas(gf,bg="white")
# gff=Frame(cgf,width=300,height=300)
xscrollbar = Scrollbar(gf, orient=HORIZONTAL)
xscrollbar.pack(side = BOTTOM, fill=X )
xscrollbar.config(command=cgf.xview)
yscrollbar = Scrollbar(gf,orient=VERTICAL)
yscrollbar.pack(side = RIGHT, fill=Y )
yscrollbar.config(command=cgf.yview)
cgf.config(xscrollcommand=xscrollbar.set, yscrollcommand=yscrollbar.set)
cgf.config(width=600,height=600)
cgf.pack(expand=1,fill=BOTH,side=RIGHT)
cgf.config(scrollregion=(0,0,1000,5000))
try:
time.sleep(5)
img = PhotoImage(file="{0}/Reports/{1}-progress.gif".format(self.workpath.get(),PL))
except:
time.sleep(5)
img = PhotoImage(file="{0}/Reports/{1}-progress.gif".format(self.workpath.get(),PL))
cgf.create_image(0,0,image=img, anchor="nw")
cgf.image=img
示例4: workflow
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import config [as 别名]
def workflow(self):
PL=self.Pipeline.get() #pipelineget()
gf=Toplevel()
#MkaS=os.popen("./makeasnake.py 2>&1 | tee -a "+workpath.get()+"/Reports/makeasnake.log").read()
gf.title("CCBR Pipeliner: "+ PL + " Workflow Graph")
cgf = Canvas(gf,bg="white")
#gff=Frame(cgf,width=300,height=300)
xscrollbar = Scrollbar(gf, orient=HORIZONTAL)
xscrollbar.pack(side = BOTTOM, fill=X )
xscrollbar.config(command=cgf.xview)
yscrollbar = Scrollbar(gf,orient=VERTICAL)
yscrollbar.pack(side = RIGHT, fill=Y )
yscrollbar.config(command=cgf.yview)
cgf.config(xscrollcommand=xscrollbar.set, yscrollcommand=yscrollbar.set)
cgf.config(width=600,height=600)
cgf.pack(expand=1,fill=BOTH,side=RIGHT)
cgf.config(scrollregion=(0,0,5000,20000))
img = PhotoImage(file=self.workpath.get()+"/Reports/"+PL+".gif")
cgf.create_image(0,0,image=img, anchor="nw")
cgf.image=img
示例5: GetText
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import config [as 别名]
self.node = node
def GetText(self):
node = self.node
if node.nodeType == node.ELEMENT_NODE:
return node.nodeName
elif node.nodeType == node.TEXT_NODE:
return node.nodeValue
def IsExpandable(self):
node = self.node
return node.hasChildNodes()
def GetSubList(self):
parent = self.node
children = parent.childNodes
prelist = [DomTreeItem(node) for node in children]
itemlist = [item for item in prelist if item.GetText().strip()]
return itemlist
data = ET.parse('irelandSetPiece.xml')
dom = data.getroot()
root = Tk()
canvas = Canvas(root)
canvas.config(bg='white')
canvas.pack()
dom = parseString(data)
item = DomTreeItem(dom.documentElement)
node = TreeNode(canvas, None, item)
node.update()
node.expand()
root.mainloop()
示例6: rmap
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import config [as 别名]
#.........这里部分代码省略.........
self.setWall('up')
if self._field[r][c].wLeft: # стена слева
self.setWall('left')
if self._field[r][c].color != '' : # закраска
self.paint(self._field[r][c].color)
if self._field[r][c].label != '' : # метка0000
d = self._d
x1 = self._size*(c)
x2 = self._size*(c+1)
y1 = self._size*(r)
y2 = self._size*(r+1)
self._canvas.delete(self._field[r][c].v.label)
self._field[r][c].v.label = self._canvas.create_rectangle(x1+d,y1+d,x2-d,y2-d, width = d-1, outline = self._field[r][c].label)
self._canvas.lift(self._robot)
self.settext(self._field[r][c].text) # текст
for self._c in range (1,self._nc):
if self._field[self._nr][self._c].wUp: # стена сверху
self.setWall('down')
for self._r in range (1,self._nr):
if self._field[self._r][self._nc].wLeft: # стена слева
self.setWall('right')
r = self._endPoint[0]
c = self._endPoint[1]
self._canvas.delete(self._park)
if r > 0 and c > 0:
self._park = self._canvas.create_oval (c*size+6,r*size+6, c*size+size-6,r*size+size-6, width = 3, outline = 'yellow')
# конечная точка
self.jumpTo((remr,remc))
self._task = '\n'+self._task
self.task.config(text = self._task)
self.res.config()
self._update()
self.sleep = sleep
#self.pause()
def _update(self):
"Обновить canvas"
if not self._NoneUpdate:
self._canvas.update()
time.sleep(self.sleep)
def start(self,fun):
self.solve_task = fun
self._tk.mainloop()
##Робот
def pause(self,t=1):
"""Приостановка выполнения программы. Пауза в секундах.
#-------------------
r.pause() # пауза в одну секунду
#-------------------
r.pause(2) # пауза две секунды
#-------------------
"""
time.sleep(t)
def left(self, a = 1):
"""Шаг влево
示例7: BoardArea
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import config [as 别名]
class BoardArea(Observer):
'''
Represent the area in which the player will play.
@ivar _selection: the current cell selected to move.
If there's no selection, the value is None.
'''
def __init__(self, game, parent):
'''Initialize the canvas, the observers and the mouse bindings.'''
Observer.__init__(self)
self._game = game
self._game.add_observer(self, 'CELL_OFF')
self._game.add_observer(self, 'CELL_ON')
self._canvas = Canvas(parent, width=280, height=280)
self._canvas.config(bg=CONFIG['BOARD_BG_COLOR'])
self._canvas.grid(row=0, columnspan=4)
self._canvas.bind("<Button-1>", self.left_button_pressed)
self._selection = None
def get_selection(self):
'''Getter of _selection.'''
return self._selection
def set_selection(self, sel):
'''Setter of _selection.'''
self._selection = sel
def left_button_pressed(self, event):
'''The mouse left button was pressed, so if there's no
selection, it's created, and if the selection exists,
attempt to make a movement taking the selection position
and the current position.'''
pos = self.get_position_from_pixels(event.x, event.y)
if pos is not None:
if self.get_selection() is None:
self.set_selection(pos)
self.make_selection(pos)
else:
move_command = Move(self._game, self.get_selection(), pos)
move_command.execute()
self.clear_selection(self.get_selection())
self.set_selection(None)
def make_selection(self, pos):
'''A selection was made.'''
self.draw_sel_rect_from_pos(pos, CONFIG['BOARD_SEL_COLOR'])
def clear_selection(self, pos):
'''No longer selection in the position given.'''
self.draw_sel_rect_from_pos(pos, CONFIG['BOARD_BG_COLOR'])
def draw_sel_rect_from_pos(self, pos, color):
'''Draw the selection rectangle.'''
rect_size = CONFIG['BOARD_RECT_SIZE']
origin_x = pos[1] * rect_size
origin_y = pos[0] * rect_size
self._canvas.create_rectangle(origin_x, origin_y, \
origin_x + rect_size, origin_y + rect_size, outline=color)
def update(self, aspect, value):
'''The board organisation in the model has changed.'''
if aspect == 'CELL_ON':
self.draw_circle_from_pos(value, CONFIG['CELL_COLOR'])
elif aspect == 'CELL_OFF':
self.draw_circle_from_pos(value, CONFIG['HOLE_COLOR'])
def draw_circle_from_pos(self, pos, color):
'''Draw a cell empty or not empty.'''
rect_size = CONFIG['BOARD_RECT_SIZE']
dist = CONFIG['DIST']
origin_x = pos[1] * rect_size + dist
origin_y = pos[0] * rect_size + dist
corner_x = origin_x + rect_size - dist * 2
corner_y = origin_y + rect_size - dist * 2
self._canvas.create_oval(origin_x, origin_y, \
corner_x, corner_y, fill=color)
def get_position_from_pixels(self, x_coord, y_coord):
'''Get the board position corresponding with the
coordinates given.'''
pos_y = int(x_coord / CONFIG['BOARD_RECT_SIZE'])
pos_x = int(y_coord / CONFIG['BOARD_RECT_SIZE'])
if (pos_x, pos_y) in self._game.get_board():
return (pos_x, pos_y)
else:
return None
示例8: GraphView
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import config [as 别名]
class GraphView(View):
WIN_PADDING_Y = 16
POINT_MARGIN = 2
def __init__(self, params):
super(GraphView, self).__init__(params)
self._ids = params["ids"] if "ids" in params else ""
self._ids = [int(i) for i in self._ids.split(' ')]
self._labels = params["labels"] if "labels" in params else ""
self._labels = [l for l in self._labels.split(' ')]
self._colors = [c for c in params["colors"].split(' ')] if "colors" in \
params else None
if not self._colors:
self._colors = self._get_auto_colors(len(self._ids))
if not len(self._ids) == len(self._labels) == len(self._colors):
raise RuntimeError("ids, labels and colors must share the same size")
self._min = float(params["min"]) if "min" in params else -1000
self._max = float(params["max"]) if "max" in params else 1000
if self._min > self._max:
self._min, self._max = self._max, self._min
self._diff = abs(self._max - self._min)
self._data = [_GraphData() for _ in range(len(self._ids))]
self._data_view = [_GraphDataView(self._colors[i]) for i in range(
len(self._ids))]
self._graph_x = 0
self._tk = Tk()
self._tk.title("Graph view %s" % str(self._labels))
self._canvas = Canvas(self._tk, width = 640, height = 480)
self._canvas.pack(fill = tkinter.BOTH, expand = 1)
self._tk.update()
self._win_size = self._tk.winfo_width(), self._tk.winfo_height()
# graph_rect only works as providing the area but not coord
self._graph_rect = self._win_size
self._tk.minsize(320, 240)
self._tk.protocol("WM_DELETE_WINDOW", self.on_press_close)
self._tk.bind("<Configure>", self.on_config)
self._canvas.config(background = config.COL_GREY_900)
self._full_redraw()
self._file = open("graph_%s_%i.csv" % (str(self._labels),
int(time.time() * 1000)), "w")
self._file.write(','.join(self._labels) + '\n')
self._tk.after(16, self._refresh)
def run(self):
super(GraphView, self).run()
self._tk.mainloop()
def on_new_input(self):
try:
hex_data = binascii.unhexlify(self.get_input())
except TypeError as e:
logging.debug(str(e))
return
count = int(len(hex_data) / GraphView._MSG_SIZE)
for i in (x * 6 for x in range(count)):
if hex_data[i] in self._ids:
value_type = hex_data[i + 1]
value_bytes = hex_data[i + 2:i + 6]
if value_type == GraphView._MSG_TYPE_INT:
value = int.from_bytes(value_bytes, byteorder = "big",
signed = True)
elif value_type == GraphView._MSG_TYPE_FLOAT:
value = struct.unpack(">f", value_bytes)[0]
else:
logging.error("Unknown type: " + str(value_type))
continue
self._tk.after_idle(self._put_value, hex_data[i], value)
def on_dismiss(self):
self._tk.after_idle(self.on_press_close)
def on_press_close(self):
self._tk.destroy()
self.join_io_thread()
def on_config(self, event):
win_size = (event.width, event.height)
if win_size != self._win_size:
self._win_size = win_size
self._full_redraw()
def is_test_input(self):
return False
def gen_test_input(self):
while True:
for i in range(int(self._min), int(self._max)):
sleep(0.1)
yield "0000%08x" % (random.randrange(-100, 100) & 0xFFFFFFFF) \
#.........这里部分代码省略.........
示例9: __init__
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import config [as 别名]
class App:
def __init__(self, master):
frame = Frame(master, borderwidth=5)
frame.grid(column=0, row=0, pady=5)
self.state = []
self.states = 256
self.laststate = 2 # 0=Black, 1=White, 2=Transp.
self.size = 16
self.gridsz = 20
for x in range(1024):
self.state.append(2)
self.screen = Canvas(frame, height=320, width=320, bg=color[2])
self.screen.bind("<Button-1>", self.scrnclick1)
self.screen.bind("<Button-3>", self.scrnclick2)
self.screen.bind("<B1-Motion>", self.scrndrag)
for x in range(16):
self.screen.create_line((x * 20, 0, x * 20, 320), fill=color[3])
self.screen.create_line((0, x * 20, 320, x * 20), fill=color[3])
self.screen.grid(row=0, column=0, columnspan=5)
frame2 = Frame(master, borderwidth=5)
frame2.grid(column=0, row=1, pady=5)
self.clear = Button(frame2, text="Clear", command=self.clearit)
self.clear.grid(row=0, column=0, pady=20)
self.doit = Button(frame2, text="Print", command=self.doit)
self.doit.grid(row=0, column=1, pady=20)
#self.doitlab = Label(frame2, text="(Output to stdout)");
#self.doitlab.grid(row=1, column=1);
self.parse = Button(frame2, text="Parse", command=self.parsetext)
self.parse.grid(row=0, column=2, pady=20)
self.large = 0
self.dummy = IntVar()
self.largeb = Checkbutton(frame2, text="Large", var=self.dummy, command=self.changesize)
self.largeb.grid(row=0, column=3, pady=20)
self.prev = Canvas(frame2, height=17, width=17, bg=color[2], relief=RIDGE)
self.prev.grid(row=0, column=4, pady=20, padx=20)
# DataParsers
self.bmlabel = Label(frame2, text="Bitmap Data (paste hex from code)")
self.bmlabel.grid(row=2, column=0, columnspan=5, sticky="W")
self.bmentry = Text(frame2, width=80, height=9, font="Times 8")
self.bmentry.bind("<Leave>", self.bmtextpaste)
self.bmentry.grid(row=3, column=0, columnspan=5, pady=5)
self.msklabel = Label(frame2, text="Mask Data (paste hex from code)")
self.msklabel.grid(row=4, column=0, columnspan=5, sticky="W")
self.mskentry = Text(frame2, width=80, height=9, font="Times 8")
self.mskentry.bind("<Leave>", self.msktextpaste)
self.mskentry.grid(row=5, column=0, columnspan=5, pady=5)
def changesize(self):
self.large = ~self.large
if self.large:
self.size = 32
self.gridsz = 10
self.states = 1024
oldstate = self.state
self.state = []
for n in range(1024):
col = (n // 2) % 16
row = int(n // 64)
self.state.append(oldstate[16 * row + col])
oldstate = []
else:
self.size = 16
self.gridsz = 20
self.states = 256
oldstate = self.state
self.state = []
for n in range(1024):
if not((n % 2) or ((n // 32) % 2)):
self.state.append(oldstate[n])
for n in range(256, 1024):
self.state.append(2)
oldstate = []
# Insert scaling here
self.updatescrn()
self.prev.config(width=self.size + 1, height=self.size + 1)
for n in range(self.states):
self.updateprev(n)
#self.prev.grid(row=0, column=4, padx=self.gridsz, pady=self.gridsz)
def scrnclick1(self, event):
#.........这里部分代码省略.........