How to put labels into frames with tkinter? - python

I'm trying to create two frames and to put 2 labels into te second one. This is my code:
import tkinter as tk
root = tk.Tk()
root.geometry("500x500")
f1 = tk.Frame(root, bg = "red", width = 400, height = 250)
f2 = tk.Frame(root, bg = "blue", width = 400, height = 150)
f1.pack()
f2.pack()
text1 = tk.Label(f2, text = "lala")
text1.pack(side='left')
text2 = tk.Label(f2, text = "lalala")
text2.pack(side= "right")
root.mainloop()
Why do neither the backgroundcolour of f2 nor the side settings work?
When I run the code, it looks like this:
I want it to look like this:
Thank you.

Here is the example with f2.pack_propagate(0) added, plus the addition of anchor keywords to more closely match the example output above (thanks acw1668)
import tkinter as tk
root = tk.Tk()
root.geometry("500x500")
f1 = tk.Frame(root, bg = "red", width = 400, height = 250)
f2 = tk.Frame(root, bg = "blue", width = 400, height = 150)
f1.pack()
f2.pack()
f2.pack_propagate(0)
text1 = tk.Label(f2, bg='blue', text = "lala")
text1.pack(side='left', anchor='n')
text2 = tk.Label(f2, bg='blue', text = "lalala")
text2.pack(side= "right", anchor='n')
root.mainloop()

Related

Why is the font in tkinter not changing in size even though I am changing the number? [duplicate]

This question already has an answer here:
Change size of text on label by Tkinter
(1 answer)
Closed 12 months ago.
So basically I have this GUI on tkinter and I want to change the size of the text on a label, this is my code:
Import tkinter as tk
#Main Page Attributes
main_frame = tk.Tk()
main_frame.attributes("-fullscreen", True)
main_frame["bg"] = "#000000"
main_frame.title("R-Net")
label_frame = tk.Frame(main_frame)
answer_label = tk.Label(label_frame, text="Welcome, Radwan", font=(70), bg = "black",fg = "white")
answer_label.grid(row=0, column=0, sticky = tk.EW)
label_frame.place(relx=.5, y=0, anchor="n")
No matter how many times I change the number in font=(number) nothing changes. Why is that?
You must actually give a font such as:
font = ("Courier", 70)
So:
answer_label = tk.Label(label_frame, text="Welcome, Radwan", font=(70), bg = "black",fg = "white")
Should instead be:
answer_label = tk.Label(label_frame, text="Welcome, Radwan", font = ("Courier", 70), bg = "black",fg = "white")

How can I run python script inside a frame in tkinter?

I have a function that asks the user to answer a couple of question which prints out a result I have written my code inside a function called Script and I made it so when I press a button the function runs but in my terminal while I want it to run inside the frame I created
Here is my code:
from tkinter import *
def Script():
#My script/code is written here
root = tk.Tk()
root.configure(background = "#110a60")
canvas = tk.Canvas(root, height = 750, width = 800, bg = "#110a60")
canvas.pack()
root.resizable(False, False)
frame = tk.Frame(root, bg = "black")
frame.place(relheight = 0.8, relwidth = 0.8, relx = 0.1, rely = 0.1)
start_button = Button(root, text = 'Start Program', padx = 10, pady = 5, fg = "#FFFF00", bg = "#012456", command = Script)
start_button.place(x = 350, y = 680)
exit_button = Button(root, text = 'Exit', padx = 20, pady = 5, fg = "#FFFF00", bg = "#012456", command = exit)
exit_button.place(x = 368, y = 714.5 )
root.mainloop()
So how can I make it when I press the Start program button the text and input outputting to the terminal/console be printed inside the frame I made(inside the red borders)
And Thanks in advance
Simple answer: You can't. print() is for the console.
More elaborate answer:
You'll probably need a Label() widget for your questions and a Entry() widget for user input. Also your script() function should not print but return a string which you can then display in a Text() widget.
Edit (added some code to your code to get you going):
from tkinter import Tk, Canvas, Frame, Button, Label, Entry, StringVar, Text
def my_script():
questions=["What is your name?",
"What is your age?"]
answers = []
answer_box.config(background='grey')
answer_box.focus()
for question in questions:
question_label.config(text=question)
answer_box.wait_variable(answer_given)
answers.append(answer_box.get())
answer_box.delete(0, 'end')
answer_box.focus()
for answer in answers:
print_area.insert('end', answer+"\n")
root = Tk()
root.configure(background = "#110a60")
canvas = Canvas(root, height = 750, width = 800, bg = "#110a60")
canvas.pack()
root.resizable(False, False)
frame = Frame(root, bg = "black")
frame.place(relheight = 0.8, relwidth = 0.8, relx = 0.1, rely = 0.1)
start_button = Button(root, text = 'Start Program', padx = 10, pady = 5, fg = "#FFFF00", bg = "#012456", command = my_script)
start_button.place(x = 350, y = 680)
exit_button = Button(root, text = 'Exit', padx = 20, pady = 5, fg = "#FFFF00", bg = "#012456", command = exit)
exit_button.place(x = 368, y = 714.5 )
question_label = Label(frame, text="", bg='black', fg='white')
question_label.place(relx=0.5, y=80, anchor='center')
answer_given = StringVar()
answer_box = Entry(frame, bg='black', borderwidth=0)
answer_box.place(relx=0.5, y=110, anchor='center')
answer_box.bind('<Return>', lambda x: answer_given.set("foobar"))
print_area = Text(frame, bg='black', fg='white')
print_area.place(relx=0.5, y=180, height=300, width=500, anchor='n')
root.mainloop()

Python: Hide / Delete label when I click on the entrybox

I am trying to hide the labels made with Canvas when I go to click on the entrybox
not when I write but simply on the click
How can I proceed?
Thanks in advance
import tkinter as tk
def handle_click():
mainCanvas.itemconfig(1, state='hidden')
window = tk.Tk()
window.geometry("500x300")
window.title("window")
mainCanvas = tk.Canvas(window, width = 500, height = 300)
mainCanvas.pack(fill = "both", expand = True)
text_input_name = tk.Entry(window, width = 25)
text_input_name_canvas = mainCanvas.create_window(250, 100, window = text_input_name)
text_input_name.bind("<1>", handle_click)
mainCanvas.create_text(250, 200, text="text", font=("Helvetica", 18), fill="red")
if __name__ == "__main__":
window.mainloop()
You already have the solution. Instead of passing 1 you need to pass the tag/id of the text. If you want to delete it, use canvas.delete(tag_or_id)
Here is an example.
import tkinter as tk
def handle_click(event):
mainCanvas.itemconfig(text, state='hidden')
#mainCanvas.delete(text)
window = tk.Tk()
window.geometry("500x300")
window.title("window")
mainCanvas = tk.Canvas(window, width = 500, height = 300)
mainCanvas.pack(fill = "both", expand = True)
text_input_name = tk.Entry(window, width = 25)
text_input_name_canvas = mainCanvas.create_window(250, 100, window = text_input_name)
text_input_name.bind("<1>", handle_click)
text = mainCanvas.create_text(250, 200, text="text", font=("Helvetica", 18), fill="red")
if __name__ == "__main__":
window.mainloop()

How to use an OptionMenu in Python Tkinter to set the justify option in a text box

I am creating a word editor in which I would like a taskbar at the top which has an OptionMenu widget with 3 possible choices - "right", "left", and "center". When one of these choices are chosen, it should take the value of that choice and set a text box window to each of those values using .tag_add, .insert, and .tag_config. Here is my code so far. All of it is inside of a frame called Task1, and the text box itself is inside a frame called label_frame. Next, the taskbar and the OptionMenu widget is inside a frame called Taskbar1. Here is my full code, which makes the GUI work.
from tkinter import *
from tkinter import ttk
from tkinter.scrolledtext import ScrolledText
import tkinter as tk
from tkinter import Menu, filedialog
root = Tk()
class ToDoList(tk.Frame):
def __init__(self, master):
root.columnconfigure(2, weight=1)
root.rowconfigure(1, weight=1)
root.title("To - Do List")
root.geometry("1200x600")
root.configure(background = "white")
# Variable list:
style = ttk.Style()
current_theme =style.theme_use()
style.theme_settings(current_theme, {"TNotebook.Tab": {"configure": {"padding": [20, 5], "background" : "white"}}})
style.theme_settings(current_theme, {"TNotebook" : {"configure" : {"tabposition" : "wn", "padding" : (0, 5)}}})
style.theme_settings(current_theme, {"TNotebook.Window" : {"configure" : {"width" : 500}}})
TasksList = ttk.Notebook(root)
Task1 = tk.Frame(TasksList, bg='white', height = 1000, width = 3000)
Taskbar1 = tk.Frame(Task1, bg="white", width=176)
Taskbar1.pack()
Button(Taskbar1, text="Hello", highlightthickness=0, borderwidth=0, highlightbackground = "white").pack(pady=[4, 5], padx=[3,3], ipadx = [2], ipady = [2], side = LEFT)
JustifyOptionList = ["right", "center", "left"]
JustifyDefaultOption=StringVar(Taskbar1)
JustifyDefaultOption.set(JustifyOptionList[0]) # default choice
JustifyOption= OptionMenu(Taskbar1, JustifyDefaultOption, *JustifyOptionList)
JustifyOption.pack(side = LEFT)
JustifyDefaultOption
entry1 = Entry(Task1, width = 60, font = "Calibri 20", highlightthickness = 0, justify = "center", selectborderwidth = 0, bd = 1, borderwidth = 0, relief = FLAT)
entry1.pack()
label_frame = tk.Frame(Task1, width=1000,height=550,bg="blue")
label_frame.pack()
label_frame.columnconfigure(0, weight=2)
label_frame.rowconfigure(0, weight = 1)
label_frame.pack_propagate(0)
# create a Text widget
root.txt = tk.Text(label_frame)
root.txt.config(font=("TkMenuFont"), undo=True, wrap='word', highlightthickness=0, borderwidth=0, bd = 1, highlightbackground = "white", spacing1 = 5, spacing2 = 5, spacing3 = 5)
root.txt.tag_config(JustifyDefaultOption.get(), justify = JustifyDefaultOption.get())
root.txt.insert("1.0", "Please enter your notes here")
root.txt.tag_add(JustifyDefaultOption.get(), "1.0", "end")
root.txt.pack(expand=TRUE, fill = "both", side = LEFT)
# create a Scrollbar and associate it with txt
scrollb = tk.Scrollbar(label_frame, command=root.txt.yview, width = 16, bg = "white", troughcolor = "white", highlightbackground = "white")
scrollb.pack(fill = Y, side = RIGHT)
root.txt['yscrollcommand'] = scrollb.set
Task2 = tk.Frame(TasksList, bg='white')
text=ScrolledText(Task2, width = 176, height = 120, font = "TkMenuFont")
text.grid(row = 2, column = 0)
entry2 = Entry(Task2, width = 179, font = "TkMenuFont")
entry2.grid(row=0, column=0, sticky = W)
Task3 = tk.Frame(TasksList, bg = "white")
text=ScrolledText(Task3, width = 176, height = 120, font = "TkMenuFont")
text.grid(row = 2, column = 0)
entry3 = Entry(Task3, width = 179, font = "TkMenuFont")
entry3.grid(row=0, column=0, sticky = W)
TasksList.add(Task1,text = 'Click Here In Order To Read The Instructions')
TasksList.add(Task2, text = 'Two Two Two Two Two Two'[0: 40] + '...')
TasksList.add(Task3, text = "Three Three Three Three Three Three Three Extra"[0 : 40] + '...')
TasksList.grid(row=1, column=0, sticky=N+W, columnspan=3)
Button(root, text = "WELCOME", borderwidth=0, highlightthickness=0).grid(row=0, column=1, sticky=E, ipady = [5])
Label(text="HELLO", borderwidth=0, highlightthickness=0).grid(row=0, column=0, sticky=W, ipady = [5])
root.mainloop()
The part that I am confused about regarding this is the fact that even though I have a OptionList that records the option that the user selects, this option is not set in the justify settings even though I am using a .get function to take the user's justify setting and apply it to the text box.
The problem is that you do not change the justify setting each time the option changes. Initializing with .get does not make the value update when the StringVar value changes.
One way of applying the new justify setting to the text is to use the command option of the OptionMenu to do it:
import tkinter as tk
def justify_text(option):
"""Change text justify setting."""
text.tag_configure('justify', justify=option)
# make sure all text has the tag
text.tag_add('justify', '1.0', 'end')
root = tk.Tk()
options = ["right", "center", "left"]
var = tk.StringVar(root, options[0])
menu = tk.OptionMenu(root, var, *options, command=justify_text)
menu.pack()
text = tk.Text(root)
text.insert('1.0', "Please enter your notes here", 'justify')
text.tag_configure('justify', justify=options[0])
text.pack()
root.mainloop()

Centering widgets in Tkinter frame using .pack()

I'm trying to get all of my labels and input boxes to be shifted down to the middle of the screen using the .pack() method. I tried using
anchor = CENTER
with the.place() method but that made everything overlap in the center. How can I simply shift all of my widgets to the center of my Tkinter frame?
Here's my code:
from Tkinter import *
root = Tk()
root.minsize(width = 500, height = 500)
root.wm_title("Email Program v1.0")
def callback():
print ("Hello!")
#sign in - email
usernameLabel = Label(root, text = "Email:")
usernameLabel.pack(padx = 0, pady = 0)
usernameInput = Entry(root)
usernameInput.pack()
usernameInput.focus_set()
passwordLabel = Label(root, text = "Password:")
passwordLabel.pack()
passwordInput = Entry(root, show = "*", width = 20)
passwordInput.pack()
passwordInput.focus_set()
#submit email credentials - connect to the server
submitEmail = Button(root, text = "Submit", fg = "black", width = 10, command = callback)
submitEmail.pack()
root.mainloop()
I managed to put those labels and entries to the center using three frames, two without any content just to 'eat' space.
frame1 = Frame(root)
frame1.pack(expand=True)
frame2 = Frame(root)
usernameLabel = Label(frame2, text = "Email:")
usernameLabel.pack(padx = 0, pady = 0)
usernameInput = Entry(frame2)
usernameInput.pack()
usernameInput.focus_set()
passwordLabel = Label(frame2, text = "Password:")
passwordLabel.pack()
passwordInput = Entry(frame2, show = "*", width = 20)
passwordInput.pack()
passwordInput.focus_set()
submitEmail = Button(frame2, text = "Submit", fg = "black", width = 10, command\
= callback)
submitEmail.pack()
frame2.pack(anchor=CENTER)
frame3 = Frame(root)
frame3.pack(expand=True)
The simple solution is to put all the widgets in a frame, and then center the frame.

Categories

Resources