Creating Tkinter Text and making previous text go up - python

I am creating a game similar to bitlife in Tkinter. Although I have run into a problem. If you recall from bitlife, or any texting platform, you create text, then all the previously created text goes up. This existing text will then go into a scrollable frame (which I have already achieved). I am not asking for the straight up code, just any methods or ideas on how to make the previously created text go up. Thanks!

Not complete but I'm out of time.
Hacked together to show you how to add items to a canvas that very loosely looks like a text message application. Not pretty at all but I only had 10 mins
import tkinter as tk
class Message(tk.Frame):
def __init__(self,parent,name,text):
super().__init__(parent,width=250)
self.lblName = tk.Label(self, text=name, font=('Arial','10'))
self.lblName.grid(row=0,column=0)
self.lblText = tk.Message(self, text=text, font=('Arial','14'))
self.lblText.grid(row=1,column=1)
class MessageFrame(tk.Frame):
def __init__(self,parent):
super().__init__(parent)
# Add a canvas in that frame
self.canvas = tk.Canvas(self, bg="yellow")
self.canvas.grid(row=0, column=0, sticky="news")
# Link a scrollbar to the canvas
self.vsb = tk.Scrollbar(self, orient="vertical", command=self.canvas.yview)
self.vsb.grid(row=0, column=1, sticky='ns')
self.canvas.configure(yscrollcommand=self.vsb.set)
# Create a frame to contain the buttons
self.frame_buttons = tk.Frame(self.canvas, bg="blue")
self.canvas.create_window((0, 0), window=self.frame_buttons, anchor='nw')
self.messages = []
self.msgItems = []
def add_message(self, sender, text):
self.messages.append({'name':sender,'text':text})
self.refresh_msg_list()
def refresh_msg_list(self):
if self.msgItems:
for item in self.msgItems:
item.destroy()
self.msgItems = []
for idx,msg in enumerate(self.messages):
newItem = Message(self.frame_buttons, msg['name'], msg['text'])
#newItem = tk.Button(self.frame_buttons, text=task['task'])
newItem.grid(row=idx,column=0,sticky='news',pady=10)
self.msgItems.append(newItem)
# Update buttons frames idle tasks to let tkinter calculate buttons sizes
self.frame_buttons.update_idletasks()
# Resize the canvas frame to fit 5 messages
first5rows_height = max([task.winfo_height() for task in self.msgItems]) * 5
item_width = max([task.winfo_width() for task in self.msgItems])
##frame_canvas.config(width=first5columns_width + vsb.winfo_width(),
## height=first5rows_height)
self.config(height=first5rows_height,width=item_width+self.vsb.winfo_width())
# Set the canvas scrolling region
self.canvas.config(scrollregion=self.canvas.bbox("all"))
def add_new_item():
pass
def add_first_item():
msg.add_message('SenderName','How are you?')
msg.add_message('SenderName','How are you?')
msg.add_message('SenderName','How are you?')
msg.add_message('SenderName','How are you?')
msg.add_message('SenderName','How are you?')
root = tk.Tk()
root.grid_rowconfigure(0, weight=1)
root.columnconfigure(0, weight=1)
frame_main = tk.Frame(root, bg="gray")
frame_main.grid(sticky='news')
# Create a frame for the canvas with non-zero row&column weights
msg = MessageFrame(frame_main)
msg.grid(row=2, column=0, pady=(5, 0), sticky='nw')
msg.grid_rowconfigure(0, weight=1)
msg.grid_columnconfigure(0, weight=1)
# Set grid_propagate to False to allow 5-by-5 buttons resizing later
msg.grid_propagate(False)
root.after_idle(add_first_item)
root.after(2000,add_new_item)
root.mainloop()

Related

My scrollbar is not working although I've everything done

I have a problem with a Tkinter scrollbar. I am doing a large message app (something like messenger), but while I try to create a scrolling frame to display all messages my scrollbar isn't showing, it's empty. It's strange that when I've moved the frame with canvas and scrollbar it has worked. I have no idea what's the problem. I hope you will help me.
Here's the code (it's just a piece of it):
class MainScreen:
def __init__(self, master):
self.frame2 = LabelFrame(master, bd=0)
self.frame2.pack(expand=True, fill=BOTH)
self.msgframe = LabelFrame(self.frame2, bg="#f3f2f1", bd=0)
self.msgframe.pack(side=RIGHT, expand=True, fill=BOTH
self.mdframe = LabelFrame(self.msgframe, bg="#f3f2f1")
self.msgcanvas = Canvas(self.mdframe)
self.msgscrollbar = Scrollbar(self.mdframe, orient=VERTICAL,
command=self.msgcanvas.yview)
self.second_frame1 = LabelFrame(self.msgcanvas, bg='black')
self.msgcanvas.config(yscrollcommand=self.msgscrollbar.set,
bg="green")
self.msgcanvas.configure(
scrollregion=self.msgcanvas.bbox("all"))
self.msgcanvas.create_window((0, 0),
window=self.second_frame1, anchor="nw")
self.mdframe.pack(fill=BOTH, expand=1)
self.msgcanvas.pack(side=LEFT, fill=BOTH, expand=1)
self.msgscrollbar.pack(side=RIGHT, fill=Y)
It looks like that:
enter image description here

How to add a scrollbar to tinker-gui tool?

I'm working on a resume-parser from this link here,
I've cloned it using,
git clone https://github.com/John-8704/ResumeFilter.git
and then just execute:
python utils/create_training_data.py
This just open the tinker GUI tool required for manually annotate data but it doesn't have a scroll bar to scroll through.
So I've edited that script i.e.,create_training_data.py in it I've modified the resume_gui function with below code to add scroll bar functionality but even then the scroll bar is not visible. How can I add scrollbar to it.
To reproduce,
Just clone the repo and try running python utils/create_training_data.py
def resume_gui(training_data_dir_path, index, file_path, file_content):
lines_with_dummy_labels = [[line, -1, -1] for line in file_content]
master = Tk()
master.columnconfigure(0, weight=1)
master.rowconfigure(0, weight=1)
master.geometry("{0}x{1}+0+0".format(master.winfo_screenwidth(),
master.winfo_screenheight()))
canvas = Canvas(master, width=170, height=300)
vsb = Scrollbar(master, orient="vertical", command=canvas.yview)
canvas.grid(row=0, column=0, sticky=W + E + N + S)
vsb.grid(row=0, column=1, sticky=N+S)
gui = LabelResume(master, lines_with_dummy_labels)
def callback():
master.destroy()
output_file_path = os.path.join(training_data_dir_path, str(index)+'.csv')
if os.path.exists(output_file_path):
return
data = pd.DataFrame.from_records(lines_with_dummy_labels,columns=['text',
'type','label'])
rows_to_drop = data.loc[((data['type']== -1) | (data['label'] == -1))].index
data.drop(data.index[rows_to_drop],inplace = True,axis = 0)
data.to_csv(output_file_path,index = False)
canvas.config(yscrollcommand= vsb.set, scrollregion=canvas.bbox("all"))
master.protocol("WM_DELETE_WINDOW", callback)
gui.mainloop()
If someone can help me out I'd really appreciate it.
Looking at the LabelResume source, it is adding itself to the window (see line 31). If you comment this out, this behaviour will stop and you can then add the frame to your canvas. The code for the resume_gui is then very similar but I am adding the LabelResume frame to the canvas using canvas.create_window(0, 0, anchor=N + W, window=gui) and then ensuring that it is rendered before updating the canvas scrollregion using gui.update().
def resume_gui(training_data_dir_path, index, file_path, file_content):
lines_with_dummy_labels = [[line, -1, -1] for line in file_content]
master = Tk()
master.columnconfigure(0, weight=1)
master.rowconfigure(0, weight=1)
master.state('zoomed')
canvas = Canvas(master, width=170, height=300)
vsb = Scrollbar(master, orient="vertical", command=canvas.yview)
canvas.grid(row=0, column=0, sticky=W + E + N + S)
vsb.grid(row=0, column=1, sticky=N+S)
gui = LabelResume(master, lines_with_dummy_labels)
def callback():
master.destroy()
output_file_path = os.path.join(training_data_dir_path, str(index)+'.csv')
if os.path.exists(output_file_path):
return
data = pd.DataFrame.from_records(lines_with_dummy_labels,columns = ['text','type','label'])
rows_to_drop = data.loc[((data['type']== -1) | (data['label'] == -1))].index
data.drop(data.index[rows_to_drop],inplace = True,axis = 0)
data.to_csv(output_file_path,index = False)
canvas.create_window(0, 0, anchor=N + W, window=gui)
gui.update()
canvas.config(yscrollcommand= vsb.set, scrollregion=canvas.bbox("all"))
master.protocol("WM_DELETE_WINDOW", callback)
gui.mainloop()
In order to use a scrollbar in your code, you're going to need to make a separate frame around the main contents of your webpage since you are using a grid format in order to layout your application.
You can't use pack, grid or anything in the same Frame.
Everything within the frame will use grid layout to display, whereas the frame itself will use the pack function to show the scrollbar.
frame = Frame(master)
frame.pack(anchor=CENTER)
# relx/y makes sure it covers
# the whole area of the window.
Now instead of gridding the contents to master, grid it to the frame.
scrollbar = Scrollbar(master)
scrollbar.pack( side = RIGHT, fill=Y )
Use the code above in order to create a scrollbar that will go across your whole application vertically where frame is the wrapper around your contents.
After adding the following changes, your code should look a bit like this:
def resume_gui(training_data_dir_path, index, file_path, file_content):
lines_with_dummy_labels = [[line, -1, -1] for line in file_content]
master = Tk()
master.columnconfigure(0, weight=1)
master.rowconfigure(0, weight=1)
master.geometry("{0}x{1}+0+0".format(master.winfo_screenwidth(),
master.winfo_screenheight()))
frame = Frame(master)
frame.pack(anchor=CENTER)
scrollbar = Scrollbar(master)
scrollbar.pack( side = RIGHT, fill=Y )
canvas = Canvas(frame, width=170, height=300)
canvas.grid(row=0, column=0, sticky=W + E + N + S)
gui = LabelResume(frame, lines_with_dummy_labels)
canvas.config(yscrollcommand= vsb.set, scrollregion=canvas.bbox("all"))
gui.mainloop()

Adding buttons in TkInter on pressing button

I am having button and on pressing it I want to create new Button and new Label.
Label must have random color and must change it on pressing this button to another random color.
My code even can not add buttons correctly, there is problems with placing new(sizes are strange).
How can I improve this? And how can I later create func for new buttons which will change their label's colours, cause I dont have label's names.
import random
from tkinter import *
def color(*args):
pass
def dump( *args):
global count
Butt = Button(root, text="color ", command=color)
Butt.config(width=int(root.winfo_width() / 10), height=int(root.winfo_height() / 10))
Butt.grid(row=0, column=count)
Txt = Label(root, text="Color", bg="#" + ("%06x" % random.randint(0, 16777215)))
Txt.config(width=int(root.winfo_width() / 10), height=int(root.winfo_height() / 10))
Txt.grid(row=1, column=count)
count+=1
root.mainloop()
count=2
TKroot = Tk()
TKroot.title("Hello")
root = Frame(TKroot)
root.place(relx=0, rely=0, relheight=1, relwidth=1)
root.columnconfigure(0, weight=10)
root.columnconfigure(1, weight=10)
root.rowconfigure(0, weight=10)
root.rowconfigure(1, weight=10)
Butt = Button(root, text="Butt ON")
Butt.bind('<Button-1>', dump)
Butt.config(width=int(root.winfo_width() / 10), height=int(root.winfo_height() / 10))
Butt.grid(row=0, column=0)
Exit = Button(root, text="Quit!", command=root.quit)
Exit.config(width=int(root.winfo_width() / 10), height=int(root.winfo_height() / 10))
Exit.grid(row=0, column=1)
Txt = Label(root, text="This is a label", bg="PeachPuff")
Txt.grid(row=1, column=1, columnspan=1)
TKroot.mainloop()
print("Done")
I see a few issues with your code.
1st is you are using place for your frame.
This is going to cause issues when adding new buttons as it will not allow the window to resize correctly with the new layout.
2nd is how you are writing your code. You name your frame root and use the quit method on the frame and not on your actually root window. The way you are writing things makes it harder to follow so consider following PEP8 guidelines when writing your code.
3rd you are trying to apply mainloop to your frame in the dump function. You only ever need 1 instance of mainloop and this applies to the actual root window (Tk()).
To address your question on how to change the label color later on I would use a list to store your buttons and labels. This way we can reference their index values and apply your random color code to the labels on button click.
I have re-written most of your code to follow PEP8 and done some general clean up.
Let me know if you have any questions.
import tkinter as tk
import random
def color(ndex):
button_label_list[ndex][1].config(bg="#%06x" % random.randint(0, 16777215))
def dump():
global count, button_label_list
button_label_list.append([tk.Button(frame, text="color", command=lambda x=count: color(x)),
tk.Label(frame, text="Color", bg="#" + ("%06x" % random.randint(0, 16777215)))])
button_label_list[-1][0].grid(row=0, column=count, sticky='nsew')
button_label_list[-1][1].grid(row=1, column=count, sticky='nsew')
frame.columnconfigure(count, weight=1)
count += 1
root = tk.Tk()
count = 0
button_label_list = []
root.title("Hello")
root.rowconfigure(1, weight=1)
root.columnconfigure(2, weight=1)
frame = tk.Frame(root)
frame.rowconfigure(1, weight=1)
frame.grid(row=0, column=2, sticky='nsew', rowspan=2)
tk.Button(root, text="butt ON", command=dump).grid(row=0, column=0, sticky='nsew')
tk.Button(root, text="Quit!", command=root.quit).grid(row=0, column=1, sticky='nsew')
tk.Label(root, text="This is a label", bg="PeachPuff").grid(row=1, column=1, columnspan=1, sticky='nsew')
root.mainloop()
Results:
A window that can add new buttons and be able to change colors on each label. The main 2 buttons the window starts with are static in that they cannot be pushed out of the window like in you code example and will remain on the left anchored in place.
below an object oriented version.
Every time you press on Color button, you create a new label and a new button
and put label reference in a dictionary.
The color of the label is randomly generate.
After creation if we click on a new button we change the relative label color.
The coolest part of the script is:
command=lambda which=self.count: self.change_color(which)
lambda funcion it's used to keep a reference to the button and label just
create when we call the change_color function.
import tkinter as tk
import random
class App(tk.Frame):
def __init__(self,):
super().__init__()
self.master.title("Hello World")
self.count = 0
self.labels = {}
self.init_ui()
def init_ui(self):
self.f = tk.Frame()
w = tk.Frame()
tk.Button(w, text="Color", command=self.callback).pack()
tk.Button(w, text="Close", command=self.on_close).pack()
w.pack(side=tk.RIGHT, fill=tk.BOTH, expand=0)
self.f.pack(side=tk.LEFT, fill=tk.BOTH, expand=0)
def callback(self):
text_label = "I'm the {} label".format(self.count)
text_button = "I'm the {} button".format(self.count)
color = "#" + ("%06x" % random.randint(0, 16777215))
obj = tk.Label(self.f, text=text_label, bg=color)
obj.pack()
self.labels[self.count]=obj
tk.Button(self.f,
text=text_button,
command=lambda which=self.count: self.change_color(which)).pack()
self.count +=1
def change_color(self,which):
color = "#" + ("%06x" % random.randint(0, 16777215))
self.labels[which].config(bg=color)
def on_close(self):
self.master.destroy()
if __name__ == '__main__':
app = App()
app.mainloop()

Tkinter Dynamic scrollbar for a dynamic GUI not updating with GUI

This is related to a previous question:
Tkinter dynamically create widgets from button
At the time that I asked the previous question, I believed that it would be easy to add a scrollable frame around the dynamic GUI. Instead, I have had a single problem with the scrollbar not detecting the new frames and entry boxes after the button is pressed. How do I solve this without editing the ScrollFrame class much?
I know that the Scrollbarframe works with other widgets it is just that the dynamic component is causing issues. When I shrink the vertical size of the window past the original location of the createWidgets button, the scrollbar appears, but the scrollbar is not present for the rest of the dynamically created widgets. Does the canvas not detect that the vertical size of the frame increases with a button press?
Note: I am aware that wildcard imports are awful. I'm just using one for the example
from tkinter import *
class AutoScrollbar(Scrollbar):
# A scrollbar that hides itself if it's not needed.
# Only works if you use the grid geometry manager!
def set(self, lo, hi):
if float(lo) <= 0.0 and float(hi) >= 1.0:
# grid_remove is currently missing from Tkinter!
self.tk.call("grid", "remove", self)
else:
self.grid()
Scrollbar.set(self, lo, hi)
def pack(self, **kw):
raise TclError("cannot use pack with this widget")
def place(self, **kw):
raise TclError("cannot use place with this widget")
class ScrollFrame:
def __init__(self, master):
self.vscrollbar = AutoScrollbar(master)
self.vscrollbar.grid(row=0, column=1, sticky=N+S)
self.hscrollbar = AutoScrollbar(master, orient=HORIZONTAL)
self.hscrollbar.grid(row=1, column=0, sticky=E+W)
self.canvas = Canvas(master, yscrollcommand=self.vscrollbar.set,
xscrollcommand=self.hscrollbar.set)
self.canvas.grid(row=0, column=0, sticky=N+S+E+W)
self.vscrollbar.config(command=self.canvas.yview)
self.hscrollbar.config(command=self.canvas.xview)
# make the canvas expandable
master.grid_rowconfigure(0, weight=1)
master.grid_columnconfigure(0, weight=1)
# create frame inside canvas
self.frame = Frame(self.canvas)
self.frame.rowconfigure(1, weight=1)
self.frame.columnconfigure(1, weight=1)
def update(self):
self.canvas.create_window(0, 0, anchor=NW, window=self.frame)
self.frame.update_idletasks()
self.canvas.config(scrollregion=self.canvas.bbox("all"))
if self.frame.winfo_reqwidth() != self.canvas.winfo_width():
# update the canvas's width to fit the inner frame
self.canvas.config(width = self.frame.winfo_reqwidth())
if self.frame.winfo_reqheight() != self.canvas.winfo_height():
# update the canvas's width to fit the inner frame
self.canvas.config(height = self.frame.winfo_reqheight())
frames = []
widgets = []
def createwidgets():
global widgetNames
global frameNames
frame = Frame(o.frame, borderwidth=2, relief="groove")
frames.append(frame)
frame.pack(side="top", fill="x")
widget = Entry(frame)
widgets.append(widget)
widget.pack(side="left")
root = Tk()
o = ScrollFrame(root)
label = Label(o.frame, text = "test")
label1 = Label(o.frame, text = "test")
label2 = Label(o.frame, text = "test")
label3 = Label(o.frame, text = "test")
label.pack()
label1.pack()
label2.pack()
label3.pack()
createWidgetButton = Button(o.frame, text="createWidgets",
command=createwidgets)
createWidgetButton.pack(side="bottom", fill="x")
o.update()
root.mainloop()
This is what the window would look like if it was fully expanded
If I were to shrink the window, it should immediately create a vertical scrollbar because that would cover a widget. However, the scrollbar acts like the program was still in its initial state.
Incorrect Scrollbar(at the moment that the scrollbar appears)
You need to make sure that you update the canvas scrollregion whenever you add widgets to the inner frame. The most common solution is to bind to the frame's <Configure> event, which will fire whenever the frame changes size.
In ScrollFrame.__init__ add the following line after you create the frame:
self.frame.bind("<Configure>", self.reset_scrollregion)
Then, add this function to ScrollFrame:
def reset_scrollregion(self, event):
self.canvas.configure(scrollregion=self.canvas.bbox("all")

Tkinter Toplevel "dropdown" not taking focus

I'm trying to create a custom looking dropdown in Tkinter and I decided to go with Toplevel. Everything works as expected except for the focus isn't taking place. When the window gets created, it stays on top of my other windows, but the <Enter>/<Leave> bindings aren't working until I click on the window. Here's a rebuilt example of the exact problem.
import tkinter as tk
from tkinter import ttk
class App(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.mainframe = ttk.Frame(self)
self.init_ui()
self.mainloop()
def init_ui(self):
self.mainframe.grid(row=0, column=0, sticky='nsew')
self.rowconfigure(0, weight=1)
self.columnconfigure(0, weight=1)
self.mainframe.rowconfigure(0, weight=1)
self.mainframe.columnconfigure(0, weight=1)
l = ttk.Label(self.mainframe, text='Test ▾')
l.config(cursor='hand', font=('Helvetica', 12, 'underline'))
l.bind('<Button-1>', self.dropdown)
l.grid(row=0, column=0, padx=50, pady=(5, 300), sticky='new')
def dropdown(self, *args):
top = tk.Toplevel(self)
top.overrideredirect(1)
top.transient(self)
def create_label(n):
nonlocal top
l = tk.Label(top, text='Test{}'.format(n))
l.config(cursor='hand', relief='ridge')
l.bind('<Enter>', enter_leave)
l.bind('<Leave>', enter_leave)
l.bind('<Button-1>', lambda _: top.destroy())
l.grid(row=n, column=0)
def enter_leave(e):
# 7 = enter
# 8 = leave
if e.type == '7':
e.widget.config(bg='grey')
else:
e.widget.config(bg='white')
# populate some labels
for x in range(9):
create_label(x)
self.update_idletasks()
top_width = top.winfo_width()
top_height = top.winfo_height()
root_x = self.winfo_x()
root_y = self.winfo_y()
top.geometry('{}x{}+{}+{}'.format(
top_width, top_height,
int(root_x + (self.winfo_width() / 2)),
root_y + 50
))
if __name__ == '__main__':
App()
This is what is looks like:
If I take out top.overrideredirect(1) then it works as expected but I get it with the title bar which I don't want:
One other interesting occurrence is when I run self.update_idletasks() right before calling top.overrideredirect(1) then it again works but with a frozen title bar. I'm not sure why that doesn't happen without self.update_idletasks() (this may be a different question):
I have tried a number of combinations of the following with no wanted results:
top.attributes('-topmost', True)
top.lift(aboveThis=self)
top.focus_force()
top.grab_set()
All in all, I would just like to get the "highlighting" effect to work but with the look of image 1 with no title bar. I'm open to all other suggestions or approaches.

Categories