I have been trying all the many examples in this website about switching windows in tkinter, but all I get is the buttons from the raised frame to be stacked on top, without "hiding" the other frames
Main screen :
import tkinter as tk
import Controller.ProdutoController as viewProduto
class Main:
def __start__(self):
self.roottk = tk.Tk()
self.root = tk.Frame(self.roottk)
self.root.pack(side="top", fill="both", expand=True)
self.root.grid_rowconfigure(0, weight=1)
self.root.grid_columnconfigure(0, weight=1)
self.viewProduto = viewProduto.ProdutoController(self, self.root)
self.viewMain = MainView(self, self.root)
self.viewMain.tkraise()
self.viewMain.master.master.title("Tela Principal")
self.roottk.mainloop()
def toprodutos(self):
self.viewProduto.viewProduto.tkraise()
def tomain(self):
self.viewMain.tkraise()
class MainView(tk.Frame):
def __init__(self, ct, root):
tk.Frame.__init__(self,root)
self.startUI()
self.ct = ct
self.grid( row = 0 , column = 0, sticky = "nsew")
def startUI(self):
botaoProdutos = tk.Button(self, text = "Produtos", command = self.toprodutos , padx = 5 , pady = 5)
botaoProdutos.pack(side = "top")
botaoEntrada = tk.Button(self, text="Entrada", command=self.toentrada, padx=5, pady=5)
botaoEntrada.pack(side="top")
botaoSaida = tk.Button(self, text="Saída", command=self.tosaida, padx=5, pady=5)
botaoSaida.pack(side="top")
def toprodutos(self):
self.ct.toprodutos()
def toentrada(self):
return
def tosaida(self):
return
"Produtos" screen :
class ProdutoController:
def __init__(self, viewMain, root):
self.produtos = []
self.viewMain = viewMain
self.viewProduto = ProdutoView(root, self)
def newproduto(self, nome, preco, quantidade):
return
def listprodutos(self):
return
class ProdutoView(tk.Frame):
def __init__(self, root, ct):
tk.Frame.__init__(self, root)
self.createWidgets()
self.ct = ct
self.grid(row = 0, column = 0)
def createWidgets(self):
self.list = tk.Button(self)
self.list["text"] = "List"
self.list["command"] = self.listProdutos
self.list.pack(side="top")
def listProdutos(self):
self.ct.listprodutos()
You aren't using the "sticky" attribute to force ProdutoView to fill the row and column that it is in.
class ProdutoView(tk.Frame):
def __init__(self, root, ct):
...
self.grid(row = 0, column = 0, sticky="nsew")
Related
I want to highlight a given token inside a input text field (We can have several token highlighted) and when the user has the mouse over this token we get up dialogox.
I tried the following:
import tkinter as tk
from tkinter import *
class Example(tk.Frame):
def __init__(self, *args, **kwargs):
tk.Frame.__init__(self, *args, **kwargs)
self.l1 = tk.Label(self, text="Hover over me")
self.l2 = tk.Label(self, text="", width=40)
self.l1.pack(side="top")
self.l2.pack(side="top", fill="x")
self.inputText = tk.Text(root, height = 10, width = 70, bg = "light yellow")
self.inputText.insert('1.0', "token1 token2 token3 etc.")
self.inputText.pack()
self.display_annotate = tk.Button(self, height = 2, width = 20, text ="Annotate text", command = lambda: self.add_highlighter())
self.display_annotate.place(x = 750, y = 20)
print(self.__dict__.keys())
self.l1.bind("<Enter>", lambda event, text="text": self.on_enter(text=text))
self.l1.bind("<Leave>", self.on_leave)
def take_input(self,):
text_to_annotate = self.inputText.get("1.0", "end-1c")
print(text_to_annotate)
return text_to_annotate
def on_enter(self, text):
self.l2.configure(text=text)
def on_leave(self, event):
self.l2.configure(text="")
def add_highlighter(self):
self.inputText.tag_add("start", "1.0", "1.5")
self.inputText.bind("<Enter>", lambda event, text="ali": self.on_enter(text=text))
self.inputText.tag_config("start", background= "black", foreground= "white")
if __name__ == "__main__":
root = tk.Tk()
scrollb = tk.Scrollbar(root)
scrollb.pack(side = tk.RIGHT, fill=tk.Y)
var1 = tk.IntVar()
var2 = tk.IntVar()
root.geometry("900x500+10+10")
root.title('Annotation page')
Example(root).pack(side="top", fill="both", expand="true")
root.mainloop()
It works to highlight the concerned token 1 between the caracters 0 and 5. But it is not working when I haveover the mouse over token 1. noting that it is working for the label.
Any suggestion?
If I got you right, I've added a label when you hover over a token (together with rotating tokens)
import tkinter as tk
from tkinter import *
def on_enter(text, obj, e=None):
obj.float_lbl = Label(root, text=text)
obj.float_lbl.place(x=e.x + obj.winfo_x(), y=e.y + obj.winfo_y())
def on_leave(obj, event=None):
obj.float_lbl.destroy()
class Example(tk.Frame):
def __init__(self, *args, **kwargs):
tk.Frame.__init__(self, *args, **kwargs)
self.l1 = tk.Label(self, text="Hover over me")
self.l1.pack(side="top")
# creating new Text object with new methods and properties
self.inputText = InputText()
# creating 15 new tokens
for i in range(15):
self.inputText.add_token(f"token{i + 1}")
self.inputText.pack()
# binding rotate_tag method to button
self.display_annotate = tk.Button(self, height=2, width=20, text="Annotate text",
command=self.inputText.rotate_tag)
self.display_annotate.place(x=750, y=20)
self.l1.bind("<Enter>", lambda event, text="text": on_enter(text=text, e=event, obj=self.l1))
self.l1.bind("<Leave>", lambda event: on_leave(event=event, obj=self.l1))
class Token:
"""
Token object for InputText
"""
def __init__(self, name: str, pos: int, tag_parent: Text):
self.token_name = name
self.begin = "1." + str(pos)
self.end = "1." + str(pos + len(name))
self.parent = tag_parent
self.add_tag()
self.bind_tag()
def add_tag(self):
self.parent.tag_add(self.token_name, self.begin, self.end)
def bind_tag(self):
self.parent.tag_bind(self.token_name, "<Enter>",
lambda event, text="text": on_enter(obj=self.parent, e=event, text=self.token_name))
self.parent.tag_bind(self.token_name, "<Leave>",
lambda event, text="text": on_leave(obj=self.parent, event=event))
def highlight_tag(self):
self.parent.tag_config(self.token_name, background='red', foreground='white')
def disable_tag(self):
self.parent.tag_config(self.token_name, background='gray', foreground='black')
class InputText(Text):
"""
Text object with methods to add tokens and rotate tags
"""
def __init__(self):
super(InputText, self).__init__(root, height=10, width=70, bg="light yellow")
self.tokens = []
self.last = 0
self.current_tag = None
def add_token(self, name):
self.insert(END, name + " ")
self.tokens.append(Token(name, self.last, self))
self.last += (1 + len(name))
def rotate_tag(self):
if self.current_tag is None:
self.current_tag = 0
else:
self.tokens[self.current_tag - 1].disable_tag()
self.tokens[self.current_tag].highlight_tag()
self.current_tag = min(self.current_tag + 1, len(self.tokens) - 1)
if __name__ == "__main__":
root = tk.Tk()
scrollb = tk.Scrollbar(root)
scrollb.pack(side=tk.RIGHT, fill=tk.Y)
var1 = tk.IntVar()
var2 = tk.IntVar()
root.geometry("900x500+10+10")
root.title('Annotation page')
Example().pack(side="top", fill="both", expand="true")
root.mainloop()
I have some Radiobuttons. Depending of what Radio button was selected I want to have different Combobox values. I don't know how I can solve the problem. In a further step I want to create further comboboxes which are dependend on the value of the first.
The following code creates the list of user, but it does not show up in the combobox.
For me it is difficult to understand where the right position of functions is, and if I need a lambda function nor a binding.
import tkinter as tk
from tkinter import ttk
import pandas as pd
import os
global version
global df_MA
df_MA = []
class Window(tk.Toplevel):
def __init__(self, parent):
super().__init__(parent)
self.geometry('300x100')
self.title('Toplevel Window')
self.btn = ttk.Button(self, text='Close',command=self.destroy).pack(expand=True)
class App(tk.Tk):
def __init__(self,*args, **kwargs):
super().__init__()
# def load_input_values(self):
def set_department(department):
if department == "produktion":
working_df_complete = path_input_produktion
if department == "service":
working_df_complete = path_input_service
working_df_complete = pd.read_excel(working_df_complete)
working_df_complete = pd.DataFrame(working_df_complete)
'''set worker df'''
df_MA = working_df_complete.loc[:,'MA']
df_MA = list(df_MA.values.tolist())
def select_working_step():
return
'''Define Variable Bereich aofter clicking of radio button '''
'''SEEMS TO ME UNECCESSARY COMPLICATED, but I dont't know how to do it properly. I am no progammer'''
border = 10
spacey = 10
'''paths for input file'''
path_input_produktion = os.path.abspath('input_data\werte_comboboxen_produktion.xlsx')
path_input_service = os.path.abspath('input_data\werte_comboboxen_service.xlsx')
self.geometry('500x600')
'''Variablen for department'''
department = tk.StringVar()
department.set(" ")
'''place Frame department'''
self.rb_frame_abteilung = tk.Frame(self)
'''Radiobuttons for department'''
rb_abteilung_produktion = tk.Radiobutton(self.rb_frame_abteilung, text="Produktion", variable= department,
value="produktion", command= lambda: set_department(department.get()))
rb_abteilung_service = tk.Radiobutton(self.rb_frame_abteilung, text="Service", variable= department,
value="service", command= lambda: set_department(department.get()) )
rb_abteilung_produktion.pack(side="left", fill=None, expand=False, padx=10)
rb_abteilung_service.pack(side="left", fill=None, expand=False, padx =10)
self.rb_frame_abteilung.grid(row=5, column=1, sticky="nw", columnspan=99)
self.label_user = ttk.Label(self, text='user').grid(row=15,
column=15, pady=spacey,padx=border, sticky='w')
self.combobox_user = ttk.Combobox(self, width = 10, value= df_MA)
self.combobox_user.bind("<<ComboboxSelected>>", select_working_step)
self.combobox_user.grid(row=15, column=20, pady=spacey, sticky='w')
if __name__ == "__main__":
app = App()
app.mainloop()
´´´
I rewrote everything using indexes and removing global variables...
#!/usr/bin/python3
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
class App(tk.Tk):
"""Application start here"""
def __init__(self):
super().__init__()
self.protocol("WM_DELETE_WINDOW", self.on_close)
self.title("Simple App")
self.option = tk.IntVar()
self.departments = ('Produktion','Service')
self.df_MA_1 = ['Peter','Hans','Alfred']
self.df_MA_2 = ['Otto','Friedrich','Tanja']
self.init_ui()
self.on_reset()
def init_ui(self):
w = ttk.Frame(self, padding=8)
r = 0
c = 1
ttk.Label(w, text="Combobox:").grid(row=r, sticky=tk.W)
self.cbCombo = ttk.Combobox(w, values="")
self.cbCombo.grid(row=r, column=c, padx=5, pady=5)
r += 1
ttk.Label(w, text="Radiobutton:").grid(row=r, sticky=tk.W)
for index, text in enumerate(self.departments):
ttk.Radiobutton(w,
text=text,
variable=self.option,
value=index,
command= self.set_combo_values).grid(row=r,
column=c,
sticky=tk.W,
padx=5, pady=5)
r +=1
r = 0
c = 2
b = ttk.LabelFrame(self, text="", relief=tk.GROOVE, padding=5)
bts = [("Reset", 0, self.on_reset, "<Alt-r>"),
("Close", 0, self.on_close, "<Alt-c>")]
for btn in bts:
ttk.Button(b, text=btn[0], underline=btn[1], command = btn[2]).grid(row=r,
column=c,
sticky=tk.N+tk.W+tk.E,
padx=5, pady=5)
self.bind(btn[3], btn[2])
r += 1
b.grid(row=0, column=1, sticky=tk.N+tk.W+tk.S+tk.E)
w.grid(row=0, column=0, sticky=tk.N+tk.W+tk.S+tk.E)
def set_combo_values(self):
print("you have selected {0} radio option".format(self.option.get()))
self.cbCombo.set("")
if self.option.get() == 0:
self.cbCombo["values"] = self.df_MA_1
else:
self.cbCombo["values"] = self.df_MA_2
def on_reset(self, evt=None):
self.cbCombo.set("")
self.option.set(0)
self.set_combo_values()
def on_close(self,evt=None):
"""Close all"""
if messagebox.askokcancel(self.title(), "Do you want to quit?", parent=self):
self.destroy()
def main():
app = App()
app.mainloop()
if __name__ == '__main__':
main()
Hello, please i'm making a tkinter window with an image and two
buttons, and using those buttons previous
and next to switch between images whenever i click the buttons
the problem is that i dont know how to change the image everytime i
click one of the buttons
import tkinter as tk
from tkinter import ttk
from PIL import ImageTk, Image
import os
BASE_DIR = os.path.dirname(os.path.relpath(__file__))
image_dir = os.path.join(BASE_DIR, "my_training_face")
class MainUi(tk.Tk):
def listDir(dir):
global names
global dict
names = []
dict = {}
fileNames = os.listdir(dir)
for fileName in fileNames:
names.append(fileName)
i = 0
while i < len(names):
dict[i] = (names[i])
i = i + 1
return dict
listDir(image_dir)
def get_name(self, cmpt):
try:
self.name = names[cmpt]
return self.name
except:
return "Empty Case"
def get_nbrHab(self):
try:
self.nbr = len(names)
return self.nbr
except:
pass
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.geometry("300x400")
self.geometry("+500+100")
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
self.frames = {}
self.frames = {}
frame = StartPage(container, self)
self.frames[StartPage] = frame
frame.place(relx=0, rely=0, relwidth=1, relheight=1)
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.configure(background='white')
# self.master.configure(background='black')
self.label = tk.Label(self, text=MainUi.get_name(self,0))
self.label.pack(pady=10, padx=10)
button1 = ttk.Button(self, text="Next", width=7, command = lambda: self.next_clicked())
button1.place(relx=0.8, rely=0.9)
button2 = ttk.Button(self, text="Back", width=7, command = lambda: self.back_clicked())
button2.place(relx=0.1, rely=0.9)
self.imgs = []
self.resizing = []
self.finals = []
try:
for i in range(MainUi.get_nbrHab(self)):
self.imgs.append(Image.open(image_dir + "/" + MainUi.get_name(self, self.compteur) + "/1.jpg"))
self.resizing.append(self.imgs[i].resize((160,120), Image.ANTIALIAS))
self.finals.append(ImageTk.PhotoImage(self.resizing[i]))
except:
return
self.label_img = tk.Label(self, bg='white', image= self.finals[0])
self.label_img.image = self.finals[0]
self.label_img.place(relx=0.21, rely=0.15)
compteur = 0
def next_clicked(self):
self.label.config(text=MainUi.get_name(self,self.compteur))
print(self.compteur)
self.label_img.config(image=self.finals[self.compteur])
self.label_img.image=self.finals[self.compteur]
self.compteur += 1
def back_clicked(self):
self.compteur-=1
app = MainUi()
app.mainloop()
I usually use .config() to update the widgets for example ->
from tkinter import *
root = Tk()
label = Label(root, text='This will be updated!')
btn = Button(root, text="Update It", command=lambda : label.config(text='Its Updated!'))
btn.pack()
root.mainloop()
Same thing can be done using Images and Other Widgets Like Buttons
There is issue in your code:
class StartPage(tk.Frame):
def __init__(self, parent, controller):
...
try:
for i in range(MainUi.get_nbrHab(self)):
# "self.compteur" is not yet defined here
# also you should use "i" instead of "self.compteur"
self.imgs.append(Image.open(image_dir + "/" + MainUi.get_name(self, self.compteur) + "/1.jpg"))
...
So the correct code should be:
class StartPage(tk.Frame):
def __init__(self, parent, controller):
...
self.compteur = 0
try:
for i in range(MainUi.get_nbrHab(self)):
self.imgs.append(Image.open(os.path.join(image_dir, MainUi.get_name(self, i), "1.jpg")))
...
Note that I don't know the last argument 1.jpg is correct or not, but it seems not required.
Then the functions for Back and Next buttons should be something like below:
def next_clicked(self):
if self.compteur+1 < len(self.finals):
self.compteur += 1
self.label.config(text=MainUi.get_name(self, self.compteur))
self.label_img.config(image=self.finals[self.compteur])
#self.label_img.image=self.finals[self.compteur] # this line is not necessary actually
def back_clicked(self):
if self.compteur > 0:
self.compteur -= 1
self.label.config(text=MainUi.get_name(self,self.compteur))
self.label_img.config(image=self.finals[self.compteur])
Here is the code. This is just for reference. This is root15.png, root14.png,rot13.png respectively.
from tkinter import *
class ChangeImage:
def __init__(self,root):
self.root = root
self.root.geometry("700x600")
self.list1=[r"C:\Users\91996\Documents\Visual studio code\Visual Studio\rot13.png",r"C:\Users\91996\Documents\Visual studio code\Visual Studio\root15.png",r'C:\Users\91996\Documents\Visual studio code\Visual Studio\root14.png']
self.compteur=0
self.im=PhotoImage(file=self.list1[self.compteur])
self.im_lbl=Label(self.root,image=self.im)
self.im_lbl.pack()
Button(self.root,text="Next Picture",command=self.next_picture).pack(pady=5)
Button(self.root,text="Back Picture",command=self.back_picture).pack(pady=5)
def next_picture(self):
if self.compteur>=len(self.list1)-1:
pass
else:
self.compteur+=1
self.im=PhotoImage(file=self.list1[self.compteur])
self.im_lbl.config(image=self.im)
def back_picture(self):
if self.compteur<=0:
pass
else:
self.compteur-=1
self.im=PhotoImage(file=self.list1[self.compteur])
self.im_lbl.config(image=self.im)
root=Tk()
ob=ChangeImage(root)
root.mainloop()
I'm trying a simple experiment, I have 3 frames, frame 1 has two labels - "for page 2" and "for page 3", it also has 2 radio buttons corresponding to the labels. based on which radio button is selected, when the user hits the next page button, I want the button to bring the user to the selected page
this is the code -
import Tkinter as tk
class MainApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
# the main container that holds all the frames
container = tk.Frame(self)
container.pack(side = "top", fill = "both", expand = True)
container.grid_rowconfigure(0, weight = 1)
container.grid_columnconfigure(0,weight = 1)
self.frames = {}
# adding frames to the dictionary
for F in (Page1,Page2,Page3):
frame = F(container,self)
self.frames[F] = frame
frame.grid(row = 0, column = 0, sticky = "w")
self.show_frame(Page1)
def show_frame(self,page_name):
#SHOWS A FRAME WITH THE GIVEN NAME
for frame in self.frames.values():
frame.grid_remove()
frame = self.frames[page_name]
frame.grid()
#STACKING THE FRAMES
#frame = self.frames[cont]
#frame.tkraise()
class Page1(tk.Frame):
def __init__(self,parent,controller):
tk.Frame.__init__(self,parent)
lbl1 = tk.Label(self,text = "for page 2",font =("Helvetica",12,"bold"))
lbl1.grid(row=1,sticky="W")
lbl2 = tk.Label(self,text = "for page 3",font =("Helvetica",12,"bold"))
lbl2.grid(row=1,column=1,sticky="W")
btn1 = tk.Button(self, text="next page", font=('MS', 24, 'bold'))
btn1.grid(row=3,column = 0,columnspan=1)
#btn1['command'] = lambda: controller.show_frame(Page2)
self.var1 = tk.BooleanVar()
rButton1 = tk.Radiobutton(self,variable = self.var1,value=True)
rButton1.grid(row=2,sticky = "W")
rButton2 = tk.Radiobutton(self,variable = self.var1,value=False)
rButton2.grid(row=2,column=1,sticky = "W")
if self.var1.get() == 1:
btn1['command'] = lambda: controller.show_frame(Page3)
if self.var1.get() == 0:
btn1['command'] = lambda: controller.show_frame(Page2)
class Page2(tk.Frame):
def __init__(self,parent,controller):
tk.Frame.__init__(self,parent)
lbl = tk.Label(self,text="This is page 2",font=("Helvetica",12,"bold"))
lbl.pack()
class Page3(tk.Frame):
def __init__(self,parent,controller):
tk.Frame.__init__(self,parent)
lbl = tk.Label(self,text="This is page 3",font=("Helvetica",12,"bold"))
lbl.pack()
app = MainApp()
app.mainloop()
I assumed that by using a few basic conditions (located in my PageOne class) -
self.var1 = tk.BooleanVar()
rButton1 = tk.Radiobutton(self,variable = self.var1,value=True)
rButton1.grid(row=2,sticky = "W")
rButton2 = tk.Radiobutton(self,variable = self.var1,value=False)
rButton2.grid(row=2,column=1,sticky = "W")
if self.var1.get() == 1:
btn1['command'] = lambda: controller.show_frame(Page3)
if self.var1.get() == 0:
btn1['command'] = lambda: controller.show_frame(Page2)
I would be able to achieve this, but it doesn't seem to work. The conditions in my if statements are integers but to my knowledge 1 represents True and 0; False anyway? what am i doing wrong?
I think this is what you want. I didn't handle making sure the radiobutton isn't selected by default. I left that as an exercise to you. Although, if you're wanting to just switch pages like this I'd just use buttons (tk/ttk.Button), then you don't have to worry about handling the radiobutton. Although, that's just my preference either will work fine of course. You can just bind each button to switch the page. I commented the buttons out in your modified code below.
If you're wanting to create buttons / radiobuttons to have a forward / back option for each page. You can just iterate over the controllers frames to see which is the current, and create two buttons similar to the ones below to move to the other frames.
import tkinter as tk
class MainApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
# the main container that holds all the frames
container = tk.Frame(self)
container.pack(side = "top", fill = "both", expand = True)
container.grid_rowconfigure(0, weight = 1)
container.grid_columnconfigure(0,weight = 1)
self.frames = {}
# adding frames to the dictionary
for F in (Page1,Page2,Page3):
frame = F(container,self)
self.frames[F] = frame
frame.grid(row = 0, column = 0, sticky = "w")
self.show_frame(Page1)
def show_frame(self,page_name):
#SHOWS A FRAME WITH THE GIVEN NAME
for frame in self.frames.values():
frame.grid_remove()
frame = self.frames[page_name]
frame.grid()
#STACKING THE FRAMES
#frame = self.frames[cont]
#frame.tkraise()
class Page1(tk.Frame):
def __init__(self,parent,controller):
tk.Frame.__init__(self,parent)
self.controller = controller
lbl1 = tk.Label(self,text = "for page 2",font =("Helvetica",12,"bold"))
lbl1.grid(row=1,sticky="W")
lbl2 = tk.Label(self,text = "for page 3",font =("Helvetica",12,"bold"))
lbl2.grid(row=1,column=1,sticky="W")
btn1 = tk.Button(self, text="next page", font=('MS', 24, 'bold'))
btn1.grid(row=3,column = 0,columnspan=1)
#btn1['command'] = lambda: controller.show_frame(Page2)
self.var1 = tk.BooleanVar()
#rButton1 = tk.Button(self, text='Show Page 2', command=lambda: self.controller.show_frame(Page2))
#rButton1.grid(row=2, sticky="W")
#rButton2 = tk.Button(self, text='Show Page 3', command=lambda: self.controller.show_frame(Page3))
#rButton2.grid(row=2, column=1, sticky="W")
rButton1 = tk.Radiobutton(self,variable = self.var1,value=True,
command=self.switch_pages)
rButton1.grid(row=2,sticky = "W")
rButton2 = tk.Radiobutton(self,variable = self.var1,value=False,
command=self.switch_pages)
rButton2.grid(row=2,column=1,sticky = "W")
def switch_pages(self):
if not self.var1.get():
self.controller.show_frame(Page3)
else:
self.controller.show_frame(Page2)
class Page2(tk.Frame):
def __init__(self,parent,controller):
tk.Frame.__init__(self,parent)
lbl = tk.Label(self,text="This is page 2",font=("Helvetica",12,"bold"))
lbl.pack()
class Page3(tk.Frame):
def __init__(self,parent,controller):
tk.Frame.__init__(self,parent)
lbl = tk.Label(self,text="This is page 3",font=("Helvetica",12,"bold"))
lbl.pack()
app = MainApp()
app.mainloop()
I am trying to change a label automatically in python, I want it to change every half a second, this is my code for tkinter, the function being called (that is being put into "message") returns a new string every half a second, what am I doing wrong?
import Tkinter as tk
class Application(tk.Frame):
def __init__(self):
self.root = tk.Tk()
self.root.geometry("150x136")
tk.Frame.__init__(self, self.root)
self.create_widgets()
def create_widgets(self):
self.root.bind('<Return>', self.parse)
self.grid()
self.instruction = tk.Label(self, text = "QuickReader")
self.instruction.grid(row = 0, column = 0, columnspan = 4)
self.entry = tk.Entry(self)
self.entry.grid(row = 2, column = 0)
self.submit = tk.Button(self, text="Submit")
self.submit.bind('<Button-1>', self.parse)
self.submit.grid(row = 4, column = 0)
self.words = tk.Label(self, text = "Start")
self.words.grid(row = 5, column = 0, columnspan = 4)
def parse(self, event):
filename = self.entry.get()
message = open_txt(filename)
self.words.set(message)
def start(self):
self.root.mainloop()
Application().start()
To change label text, use one of following:
self.words.config(text=message)
self.words.configure(text=message)
self.words['text'] = message
http://effbot.org/tkinterbook/label.htm
You can associate a Tkinter variable with a label. When the contents of the variable changes, the label is automatically updated:
v = StringVar()
Label(master, textvariable=v).pack()
v.set("New Text!")
So, that should be pretty easy to implement.