I have a function inside a method of a class like this:
from tkinter import Frame, Tk, BOTH, Text, Menu, END
from tkinter import filedialog as tkFileDialog
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
self.path = None
print(self.path)
def initUI(self):
self.parent.title("File dialog")
self.pack(fill=BOTH, expand=1)
menubar = Menu(self.parent)
self.parent.config(menu=menubar)
fileMenu = Menu(menubar)
fileMenu.add_command(label="Open_image", command=self.onOpen1)
menubar.add_cascade(label="File", menu=fileMenu)
def onOpen1(self):
ftypes = [('jpg files','.jpg'),('png files','.png'),('all files','.*')]
dlg = tkFileDialog.Open(self, filetypes = ftypes)
path = dlg.show()
if path != '':
self.path = path
print(self.path)
return self.path
def main():
root = Tk()
ex = Example(root)
root.geometry("300x250+300+300")
root.mainloop()
if __name__ == '__main__':
main()
When I run the code, the self.path variable inside the function changes. But the self.path global variable outside the function does not change.
I would like self.path to be updated outside of the function. In fact, I want to update the self.path variable with the onOpen1 function. This function opens a window which allows you to select an image. Then, I want to recover the path of this image to update self.path.
The button is just a way to help visualize what is happening. Here is the full code.
from tkinter import Frame, Tk, BOTH, Text, Menu, END, Button
from tkinter import filedialog as tkFileDialog
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
self.path = None
print(self.path)
def initUI(self):
self.parent.title("File dialog")
self.pack(fill=BOTH, expand=1)
menubar = Menu(self.parent)
self.parent.config(menu=menubar)
fileMenu = Menu(menubar)
fileMenu.add_command(label="Open_image", command=self.onOpen1)
menubar.add_cascade(label="File", menu=fileMenu)
button = Button(self.parent, text='test', command=self.test)
button.pack()
def test(self):
print(self.path)
def onOpen1(self):
ftypes = [('jpg files','.jpg'),('png files','.png'),('all files','.*')]
dlg = tkFileDialog.Open(self, filetypes = ftypes)
path = dlg.show()
if path != '':
self.path = path
print(self.path)
return self.path
def main():
root = Tk()
ex = Example(root)
root.geometry("300x250+300+300")
root.mainloop()
if __name__ == '__main__':
main()
Run it and watch your console where the print will happen.
Hit the button. Notice how self.path is None.
Now select an image with your file dialog box.
Hit the button again. Notice how self.path changed to reflect what the path to the image is?
You stated that you want to update self.path to reflect what you selected. Your code does in fact do that. The point of this visualization is to show you that the question you asked may not be the solution to the problem you're having.
Here is an example of what I think you want.
from tkinter import Frame, Tk, BOTH, Text, Menu, END, Button, Label
from tkinter import filedialog as tkFileDialog
import cv2
from PIL import ImageTk, Image
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
self.path = None
print(self.path)
def initUI(self):
self.parent.title("File dialog")
self.pack(fill=BOTH, expand=1)
menubar = Menu(self.parent)
self.parent.config(menu=menubar)
fileMenu = Menu(menubar)
fileMenu.add_command(label="Open_image", command=self.onOpen1)
menubar.add_cascade(label="File", menu=fileMenu)
def test(self):
print(self.path)
def onOpen1(self):
ftypes = [('jpg files','.jpg'),('png files','.png'),('all files','.*')]
dlg = tkFileDialog.Open(self, filetypes = ftypes)
path = dlg.show()
if path != '':
self.path = path
self.add_image()
def add_image(self):
img = cv2.imread(self.path)
img = cv2.resize(img,(224, 224), interpolation = cv2.INTER_AREA)
image1 = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
image1 = Image.fromarray(image1)
image1 = ImageTk.PhotoImage(image1)
panelA = Label(self, image=image1)
panelA.image = image1
panelA.grid(row=0, column=0, sticky='w')
def main():
root = Tk()
ex = Example(root)
root.geometry("300x250+300+300")
root.mainloop()
if __name__ == '__main__':
main()
Here's some sample code for 2 frames.
from tkinter import Frame, Tk, BOTH, Text, Menu, END, Button, Label
from tkinter import filedialog as tkFileDialog
import cv2
from PIL import ImageTk, Image
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
self.current_window = 0
self.path = None
self.panelA = None
self.panelB = None
print(self.path)
def initUI(self):
self.parent.title("File dialog")
#self.pack(fill=BOTH, expand=1)
menubar = Menu(self.parent)
self.parent.config(menu=menubar)
fileMenu = Menu(menubar)
fileMenu.add_command(label="Open Image 1", command=lambda: self.onOpen1(1))
fileMenu.add_command(label="Open Image 2", command=lambda: self.onOpen1(2))
menubar.add_cascade(label="File", menu=fileMenu)
self.button_1 = Button(self.parent, text='Window 1', command=lambda: self.switch_window(1))
self.button_2 = Button(self.parent, text='Window 2', command=lambda: self.switch_window(2))
self.back_button = Button(self.parent, text='Back', command=lambda: self.switch_window(0))
self.button_1.grid(sticky='w')
self.button_2.grid(sticky='w')
def switch_window(self, window):
self.current_window = window
if window == 0:
self.back_button.grid_forget()
self.button_1.grid(sticky='w')
self.button_2.grid(sticky='w')
else:
self.button_1.grid_forget()
self.button_2.grid_forget()
self.back_button.grid(row=1, sticky='w')
self.repopulate_windows()
def onOpen1(self, image_selection):
ftypes = [('jpg files','.jpg'),('png files','.png'),('all files','.*')]
dlg = tkFileDialog.Open(self, filetypes = ftypes)
path = dlg.show()
if path != '':
self.path = path
self.add_image(image_selection)
def add_image(self, image_selection):
img = cv2.imread(self.path)
img = cv2.resize(img,(224, 224), interpolation = cv2.INTER_AREA)
image1 = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
image1 = Image.fromarray(image1)
image1 = ImageTk.PhotoImage(image1)
if image_selection == 1:
self.panelA = Label(self.parent, image=image1)
self.panelA.image = image1
else:
self.panelB = Label(self.parent, image=image1)
self.panelB.image = image1
if self.current_window != 0:
self.repopulate_windows()
def repopulate_windows(self):
if self.current_window == 1:
if self.panelB is not None:
self.panelB.grid_forget()
if self.panelA is not None:
self.panelA.grid(row=0, column=0, sticky='w')
elif self.current_window == 2:
if self.panelA is not None:
self.panelA.grid_forget()
if self.panelB is not None:
self.panelB.grid(row=0, column=0, sticky='w')
else:
if self.panelA is not None:
self.panelA.grid_forget()
if self.panelB is not None:
self.panelB.grid_forget()
def main():
root = Tk()
ex = Example(root)
root.geometry("300x250+300+300")
root.mainloop()
if __name__ == '__main__':
main()
Related
I am using VLC in Python to open a video stream (UDP stream).
How can I set the dimensions of the video window and its position on the screen
This is the code
import vlc
i = vlc.Instance()
p = i.media_player_new()
p.set_mrl('udp://#224.1.1.1:1234')
p.play()
In short I don't think that you can, unless your provide it with a window to play in, that you control.
This involves wrapping it within a gui, many people use Tkinter, wxPython or Qt for this. Below are samples written on Linux.
Here is a wxPython sample:
import vlc
import wx
class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, "Video Frame WxPython", size=(500,400))
self.panel = wx.Panel(self, id= -1, pos=(10,10), size=(470,300))
self.play_button = wx.Button(self, -1, "Play", pos=(10,320))
self.stop_button = wx.Button(self, -1, "Pause", pos=(100,320))
self.Bind(wx.EVT_BUTTON, self.play, self.play_button)
self.Bind(wx.EVT_BUTTON, self.stop, self.stop_button)
self.panel.SetBackgroundColour(wx.BLACK)
self.Show()
def play(self,event):
vlc_options = '--no-xlib --quiet'
inst = vlc.Instance(vlc_options)
self.player = inst.media_player_new()
self.player.set_mrl('file:///home/rolf/BBB.ogv')
xid = self.panel.GetHandle()
self.player.set_xwindow(xid)
self.player.play()
def stop(self,event):
try:
self.player.pause()
except:
pass
app = wx.App()
frame = MyFrame()
app.MainLoop()
This is a Tkinter version (forgive any quirks, I don't use Tkinter myself):
import tkinter as tk
import vlc
class myframe(tk.Frame):
def __init__(self, root, width=500, height=400, bd=5):
super(myframe, self).__init__(root)
self.grid()
self.frame = tk.Frame(self, width=450, height=350, bd=5)
self.frame.configure(bg="black")
self.frame.grid(row=0, column=0, columnspan=2, padx=8)
self.play_button = tk.Button(self, text = 'Play', command = self.play)
self.play_button.grid(row=1, column=0, columnspan=1, padx=8)
self.stop_button = tk.Button(self, text = 'Pause', command = self.pause)
self.stop_button.grid(row=1, column=1, columnspan=1, padx=8)
def play(self):
i = vlc.Instance('--no-xlib --quiet')
self.player = i.media_player_new()
self.player.set_mrl('file:///home/rolf/BBB.ogv')
xid = self.frame.winfo_id()
self.player.set_xwindow(xid)
self.player.play()
def pause(self):
try:
self.player.pause()
except:
pass
if __name__ == '__main__':
root = tk.Tk()
root.title("Video Frame Tkinter")
app = myframe(root)
root.mainloop()
This is how they look on the screen:
Im attempting to insert an image on a canvas in my tkinter GUI. I'm able to insert an image usually but when doing it on a canvas I get the errors:
"pyimage does not exist" or "file directory not found"
In the class "PageMain" I have created a widget and followed the answer on this thread - How to insert an image in a canvas item?
However it still says the file cannot be found despite using the answer.
from Tkinter import *
import ttk
import sqlite3
import Tkinter as tk
import Tkinter
import sys
import StringIO
from PIL import Image, ImageTk
import os
class MyApp(Tk):
def __init__(self):
Tk.__init__(self)
container = ttk.Frame(self)
container.pack(side="top", fill="both", expand=True)
self.frames = {}
for F in (PageMain, PageOne, PageTwo):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky='NSEW')
self.show_frame(PageMain)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
class PageMain(ttk.Frame):
def __init__(self, parent, controller):
self.controller = controller
ttk.Frame.__init__(self, parent)
self.make_widget()
def make_widget(self):
canvas = Canvas(self, width="1000", height="600")
img = PhotoImage(file='D:\plogo\logo.png')
canvas.create_image(50, 10, image=img, anchor=NW)
# demo button to change page
btnChange = Button(canvas, text="Change", font="Arial 16",
command=lambda: self.controller.show_frame(PageOne),
bg="#a0ccda")
btnChange .place(x=600, y=550, width="100", height="50")
canvas.pack()
def change_page(self):
pass
if __name__ == '__main__':
app = MyApp()
app.title('Music Match')
app.mainloop()
you must keep a reference to the image, thanks Bryan, see below, especially to
w = tk.Canvas(self,)
w.img = tk.PhotoImage(file='logo.png')
#!/usr/bin/python3
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
class Main(ttk.Frame):
def __init__(self, parent):
super().__init__()
self.parent = parent
self.init_ui()
def init_ui(self):
w = tk.Canvas(self, )
w.img = tk.PhotoImage(file='logo.png')
w.create_image(50,50, anchor=tk.N+tk.W, image=w.img)
w.pack(expand=1)
def on_close(self):
self.parent.on_exit()
class App(tk.Tk):
"""Start here"""
def __init__(self):
super().__init__()
self.protocol("WM_DELETE_WINDOW", self.on_exit)
self.set_style()
self.set_title()
frame = Main(self,)
frame.pack(fill=tk.BOTH, expand=1)
def set_style(self):
self.style = ttk.Style()
#('winnative', 'clam', 'alt', 'default', 'classic', 'vista', 'xpnative')
self.style.theme_use("clam")
def set_title(self):
s = "{0}".format('Simple App')
self.title(s)
def on_exit(self):
"""Close all"""
if messagebox.askokcancel(self.title(), "Do you want to quit?", parent=self):
self.destroy()
if __name__ == '__main__':
app = App()
app.mainloop()
I am trying to build a text editor with different tabs, and each one is a file, but the problem is that when I try to save the file, it doesn't read nothing, it creates a new file with no content. Before I didn't have the Tab class and it worked, but the problem was that it saved all the files with the same content.
Here is the code:
from tkinter import *
from tkinter import filedialog, ttk
import os
class App():
def __init__(self):
title = 'New document'
self.root = Tk()
self.root.geometry('300x200')
self.root.iconbitmap('icon.ico')
self.root.title(title)
self.tabs = {'ky': 0}
self.notebook = ttk.Notebook(self.root)
self.notebook.pack(expand = True, fill= 'both')
menubar = Menu(self.root)
# create a pulldown menu, and add it to the menu bar
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="New...", command=self.generate_tab)
filemenu.add_command(label="Open", command = self.open_file)
filemenu.add_command(label="Save", command= self.save_file)
filemenu.add_separator()
filemenu.add_command(label="Exit", command= self.root.quit)
menubar.add_cascade(label="File", menu = filemenu)
editmenu = Menu(menubar, tearoff=0)
editmenu.add_command(label="Undo")
editmenu.add_command(label="Redo")
editmenu.add_separator()
menubar.add_cascade(label="Edit", menu=editmenu)
self.root.config(menu=menubar)
def open_file(self):
file = open(filedialog.askopenfilename(), 'r+')
text_value = file.read()
self.textWidget.delete(1.0, "end-1c")
self.textWidget.insert("end-1c", text_value)
title = os.path.basename(file.name)
self.root.title(title)
file.close()
def add_tab(self, name):
tab = Tab(self.notebook, name)
print(name)
self.notebook.add(tab, text=name)
def save_file(self):
self.get_tab().save_tab()
def get_tab(self):
tab = Tab(self.notebook, 'Document ' + str(self.notebook.index('current')))
return tab
def generate_tab(self):
if self.tabs['ky'] < 20:
self.tabs['ky'] += 1
self.add_tab('Document ' + str(self.tabs['ky']))
def run(self):
self.root.mainloop()
class Tab(Frame):
def __init__(self, root, name):
Frame.__init__(self, root)
self.root = root
self.name = name
self.textWidget = Text(self)
self.textWidget.pack(expand=True, fill='both')
def save_tab(self):
print(self.textWidget.get("1.0", 'end-1c'))
file = open(filedialog.asksaveasfilename() + '.txt', 'w+')
file.write(self.textWidget.get("1.0", 'end-1c'))
print(os.path.basename(file.name))
#title = os.path.basename(file.name)
file.close()
if __name__ == '__main__':
app1 = App()
app1.run()
Problem lies with your get_tab method. It doesn't actually return the object that represents the currently open tab. It returns a new tab that has no content.
In order to fix your problem you need to keep a record of the tabs you've created. I've created a 'workable' version that adds the object of each tab to a list when they are created. This way if you are currently in "Document 3" and press save, it will get the Tab object that relates to document 3.
from tkinter import *
from tkinter import filedialog, ttk
import os
class App():
def __init__(self):
title = 'New document'
self.root = Tk()
self.root.geometry('300x200')
#self.root.iconbitmap('icon.ico')
self.root.title(title)
self.tabs = {'ky': 0}
#Keep a record of the open tabs in a list.
self.tab_list = []
self.notebook = ttk.Notebook(self.root)
self.notebook.pack(expand = True, fill= 'both')
menubar = Menu(self.root)
# create a pulldown menu, and add it to the menu bar
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="New...", command=self.generate_tab)
filemenu.add_command(label="Open", command = self.open_file)
filemenu.add_command(label="Save", command= self.save_file)
filemenu.add_separator()
filemenu.add_command(label="Exit", command= self.root.quit)
menubar.add_cascade(label="File", menu = filemenu)
editmenu = Menu(menubar, tearoff=0)
editmenu.add_command(label="Undo")
editmenu.add_command(label="Redo")
editmenu.add_separator()
menubar.add_cascade(label="Edit", menu=editmenu)
self.root.config(menu=menubar)
def open_file(self):
file = open(filedialog.askopenfilename(), 'r+')
text_value = file.read()
self.textWidget.delete(1.0, "end-1c")
self.textWidget.insert("end-1c", text_value)
title = os.path.basename(file.name)
self.root.title(title)
file.close()
def add_tab(self, name):
tab = Tab(self.notebook, name)
print(name)
self.notebook.add(tab, text=name)
self.tab_list.append(tab)
def save_file(self):
tab_to_save = self.get_tab()
print(tab_to_save)
tab_to_save.save_tab()
def get_tab(self):
print(self.notebook.index('current'))
#Get the tab object from the tab_list based on the index of the currently selected tab
tab = self.tab_list[self.notebook.index('current')]
return tab
def generate_tab(self):
if self.tabs['ky'] < 20:
self.tabs['ky'] += 1
self.add_tab('Document ' + str(self.tabs['ky']))
def run(self):
self.root.mainloop()
class Tab(Frame):
def __init__(self, root, name):
Frame.__init__(self, root)
self.root = root
self.name = name
self.textWidget = Text(self)
self.textWidget.pack(expand=True, fill='both')
def save_tab(self):
print(self.textWidget.get("1.0", 'end-1c'))
file = open(filedialog.asksaveasfilename() + '.txt', 'w+')
file.write(self.textWidget.get("1.0", 'end-1c'))
print(os.path.basename(file.name))
#title = os.path.basename(file.name)
file.close()
if __name__ == '__main__':
app1 = App()
app1.run()
i have written the "instruction" for my tkinter program on a .txt file and when the Instruction button is pressed, I would like a separate window to be created with the instruction copied from the text file into the output box.
I would be very grateful if anyone could help me.
this is what I have done so far but it doesn't work at all.
instructionBtn = Button(window, text="?", command=start, height = 5, width =30,fg="black", bg="lime green", font=("Comic Sans MS", 10))
instructionBtn.grid(row=29, column=1, sticky=S)
window.mainloop()
def instruction():
instructionwindow = Tk() #create window
instructionwindow.geometry("500x350")
instructionwindow.title("Instruction")
instructionwindow.configure(background='white')
instructionFile=open("Instruction.txt","r")
instruction.read
textboxOutput = Text(window, wrap="Instruction.txt", width = 150, height = 20)
textboxOutput.grid(row = 20, column = 0, columnspan=10)
instruction.mainloop()
When I want a second window, often a message box will do the trick, like so:
from Tkinter import *
from tkMessageBox import showinfo
class App:
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.button = Button(frame, text="QUIT", fg="red", command=frame.quit)
self.button.pack(side=LEFT)
self.instr = Button(frame, text="Instruction", command=self.instruction)
self.instr.pack(side=LEFT)
def instruction(self):
try:
with open("instruction.txt") as fp:
message = fp.read()
except IOError:
message = 'No instructions available'
showinfo("Instructions", message)
root = Tk()
app = App(root)
root.mainloop()
Or, if you prefer an OOP style:
# template: https://stackoverflow.com/a/17470842/8747
# Use Tkinter for python 2, tkinter for python 3
import Tkinter as tk
import tkMessageBox
class MainApplication(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.parent = parent
self.button = tk.Button(
self, text="QUIT", fg="red", command=self.quit)
self.instr = tk.Button(
self, text="Instruction", command=self.instruction)
self.button.pack(side=tk.LEFT)
self.instr.pack(side=tk.LEFT)
def instruction(self):
try:
with open("instruction.txt") as fp:
message = fp.read()
except IOError:
message = 'No instruction available'
msg = tkMessageBox.showinfo("Instruction", message)
if __name__ == "__main__":
root = tk.Tk()
MainApplication(root).pack(side="top", fill="both", expand=True)
root.mainloop()
Of course, sometimes a message box isn't flexible enough, and you need to create a top-level window:
# template: https://stackoverflow.com/a/17470842/8747
# Use Tkinter for python 2, tkinter for python 3
import Tkinter as tk
import tkMessageBox
class Instruction(tk.Toplevel):
def __init__(self, parent, message, *args, **kwargs):
tk.Toplevel.__init__(self, parent, *args, **kwargs)
self.msg = tk.Message(self, text=message)
self.button = tk.Button(self, text="Dismiss", command=self.destroy)
self.msg.pack()
self.button.pack()
class MainApplication(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.parent = parent
self.button = tk.Button(
self, text="QUIT", fg="red", command=self.quit)
self.instr = tk.Button(
self, text="Instruction", command=self.instruction)
self.button.pack(side=tk.LEFT)
self.instr.pack(side=tk.LEFT)
def instruction(self):
try:
with open("instruction.txt") as fp:
message = fp.read()
except IOError:
message = 'No instruction available'
msg = Instruction(self, message)
if __name__ == "__main__":
root = tk.Tk()
MainApplication(root).pack(side="top", fill="both", expand=True)
root.mainloop()
Can anyone help me to understand the window code? Im trying to make all the objects run in a Toplevel() function instead of a new instance of Tkinter because that doesn't work launching it from another program. Theres no window = Tk() function anywhere just init and frame.
from tkinter import *
from tkinter.simpledialog import askstring
from tkinter.filedialog import asksaveasfilename
from tkinter.messagebox import askokcancel
def text_edit() :
class Quitter(Frame):
def __init__(self, parent=None):
Frame.__init__(self, parent)
self.pack()
widget = Button(self, text='Quit', command=self.quit)
widget.pack(expand=YES, fill=BOTH, side=LEFT)
def quit(self):
ans = askokcancel('Verify exit', "Really quit?")
if ans: Frame.quit(self)
class ScrolledText(Frame):
def __init__(self, parent=None, text='', file=None):
Frame.__init__(self, parent)
self.pack(expand=YES, fill=BOTH)
self.makewidgets()
self.settext(text, file)
def makewidgets(self):
sbar = Scrollbar(self)
text = Text(self, relief=SUNKEN)
sbar.config(command=text.yview)
text.config(yscrollcommand=sbar.set)
sbar.pack(side=RIGHT, fill=Y)
text.pack(side=LEFT, expand=YES, fill=BOTH)
self.text = text
def settext(self, text='', file=None):
if file:
text = open(file, 'r').read()
self.text.delete('1.0', END)
self.text.insert('1.0', text)
self.text.mark_set(INSERT, '1.0')
self.text.focus()
def gettext(self):
return self.text.get('1.0', END+'-1c')
class SimpleEditor(ScrolledText):
def __init__(self, parent=None, file=None):
frm = Frame(parent)
frm.pack(fill=X)
Button(frm, text='Save', command=self.onSave).pack(side=LEFT)
Button(frm, text='Cut', command=self.onCut).pack(side=LEFT)
Button(frm, text='Paste', command=self.onPaste).pack(side=LEFT)
Button(frm, text='Find', command=self.onFind).pack(side=LEFT)
Quitter(frm).pack(side=LEFT)
ScrolledText.__init__(self, parent, file=file)
self.text.config(font=('courier', 9, 'normal'))
def onSave(self):
filename = asksaveasfilename()
if filename:
alltext = self.gettext()
open(filename, 'w').write(alltext)
def onCut(self):
text = self.text.get(SEL_FIRST, SEL_LAST)
self.text.delete(SEL_FIRST, SEL_LAST)
self.clipboard_clear()
self.clipboard_append(text)
def onPaste(self):
try:
text = self.selection_get(selection='CLIPBOARD')
self.text.insert(INSERT, text)
except TclError:
pass
def onFind(self):
target = askstring('SimpleEditor', 'Search String?')
if target:
where = self.text.search(target, INSERT, END)
if where:
print (where)
pastit = where + ('+%dc' % len(target))
#self.text.tag_remove(SEL, '1.0', END)
self.text.tag_add(SEL, where, pastit)
self.text.mark_set(INSERT, pastit)
self.text.see(INSERT)
self.text.focus()
if __name__ == '__main__':
try:
SimpleEditor(file=sys.argv[1]).mainloop()
except IndexError:
SimpleEditor().mainloop()
You have to adapt to Tkinter as it was written to be used (or write your own which is beyond me), instead of trying to pound it into some preconceived form.
try:
import Tkinter as tk ## Python 2.x
except ImportError:
import tkinter as tk ## Python 3.x
from functools import partial
class OpenToplevels():
""" open and close additional Toplevels with a button
"""
def __init__(self):
self.root = tk.Tk()
self.button_ctr=0
but=tk.Button(self.root, text="Open a Toplevel",
command=self.open_another)
but.grid(row=0, column=0)
tk.Button(self.root, text="Exit Tkinter", bg="red",
command=self.root.quit).grid(row=1, column=0, sticky="we")
self.root.mainloop()
def close_it(self, id):
id.destroy()
def open_another(self):
self.button_ctr += 1
id = tk.Toplevel(self.root)
id.title("Toplevel #%d" % (self.button_ctr))
tk.Button(id, text="Close Toplevel #%d" % (self.button_ctr),
command=partial(self.close_it, id),
bg="orange").grid(row=1, column=0)
Ot=OpenToplevels()