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()
Related
I am new to Python, trying to make the Launch TFL App button open another GUI called "Menu GUI" but I don't know what to do for the def open_Menu(): function below. I want to use the popup GUI below as a launcher which takes the user to my main GUI. The only problem with the code below is that the button for launch TFL app doesn't do anything when you click it.
Here's my current code :
from tkinter import *
root = Tk()
root.title('TFL App')
p = Label(root, text = "TFL Journey Planner", height = "18", width = "250", bg = 'brown', fg =
'white',
font = ('Helvetica', '20', 'bold', 'italic'))
p.pack()
root.configure(bg = 'brown')
root.geometry('400x700')
photo = PhotoImage(file = 'trainstation.png')
label = Label(root, image = photo)
label.pack()
****#Buttons****
def open_Menu():
pass
Button1 = Button(root, text = "Launch TFL App", command = open_Menu, bg = "black", fg = 'white', padx
= 40,
pady = 10,
font = ('Calibri Light', '15', 'bold'))
Button1.pack(padx = 25, pady = 0)
Button2 = Button(root, text = "Exit ", command = root.destroy, bg = "black", fg = 'white', padx = 65,
pady = 8,
font = ('Calibri Light', '15', 'bold'))
Button2.pack(padx = 25, pady = 10)
root.mainloop()
How can I implement open_menu()
The code below is for my Main GUI which should open through the PopUp GUI above but the button on the PopUp GUI is not working.
from tkinter import *
def find():
# get method returns current text
# as a string from text entry box
From = From_field.get()
To = To_field.get()
travel_modes = mode_field.get()
# Calling result() Function
result(From, To, travel_modes)
# Function for inserting the train string
# in the mode_field text entry box
def train():
mode_field.insert(10, "train")
# Function for clearing the contents
def del_From():
From_field.delete(0, END)
distance_field.delete(0, END)
duration_field.delete(0, END)
def del_To():
To_field.delete(0, END)
distance_field.delete(0, END)
duration_field.delete(0, END)
def del_modes():
mode_field.delete(0, END)
distance_field.delete(0, END)
duration_field.delete(0, END)
def delete_all():
From_field.delete(0, END)
To_field.delete(0, END)
mode_field.delete(0, END)
distance_field.delete(0, END)
duration_field.delete(0, END)
# Driver code
if __name__ == "__main__":
# Create a GUI root
root = Tk()
# Set the background colour of GUI root
root.configure(background = 'light blue')
# Set the configuration of GUI root
root.geometry("600x400")
# Created a welcome to distance time calculator label
headlabel = Label(root, text = 'Welcome to your TFL Journey Planner',
fg = 'white', bg = "dark red", height = "0", width = "30",
font = ('calibri light', '19', 'italic'))
# Created a From: label
label1 = Label(root, text = "From:",
fg = 'white', bg = 'black')
# Created a To: label
label2 = Label(root, text = "To:",
fg = 'white', bg = 'black')
# Created a Distance: label
label4 = Label(root, text = "Distance:",
fg = 'white', bg = 'black')
# Created a Duration: label
label5 = Label(root, text = "Duration:",
fg = 'white', bg = 'black')
label6 = Label(root, text = "Choose travelling mode Below: ",
fg = 'white', bg = 'black')
headlabel.grid(row = 0, column = 1)
label1.grid(row = 1, column = 0, sticky = "E")
label2.grid(row = 2, column = 0, sticky = "E")
label4.grid(row = 7, column = 0, sticky = "E")
label5.grid(row = 8, column = 0, sticky = "E")
label6.grid(row = 3, column = 1)
# Created a text entry box
# for filling or typing the data.
From_field = Entry(root)
To_field = Entry(root)
mode_field = Entry(root)
distance_field = Entry(root)
duration_field = Entry(root)
From_field.grid(row = 1, column = 1, ipadx = "100")
To_field.grid(row = 2, column = 1, ipadx = "100")
mode_field.grid(row = 5, column = 1, ipadx = "50")
distance_field.grid(row = 7, column = 1, ipadx = "100")
duration_field.grid(row = 8, column = 1, ipadx = "100")
# CLEAR Button and attached
# to del_source function
button1 = Button(root, text = "Clear", bg = "light grey",
fg = "black", command = del_From)
# Create a CLEAR Button and attached to del_destination
button2 = Button(root, text = "Clear", bg = "light grey",
fg = "black", command = del_To)
# Create a RESULT Button and attached to find function
button3 = Button(root, text = "Result",
bg = "black", fg = "white",
command = find)
# Create a CLEAR ALL Button and attached to delete_all function
button4 = Button(root, text = "Clear All",
bg = "light grey", fg = "black",
command = delete_all)
# Create a Train Button and attached to train function
button5 = Button(root, text = "Train",
bg = "light grey", fg = "black",
command = train)
# Create a CLEAR Button and attached to del_modes function
button6 = Button(root, text = "Clear",
fg = "black", bg = "light grey",
command = del_modes)
button1.grid(row = 1, column = 2)
button2.grid(row = 2, column = 2)
button3.grid(row = 6, column = 1)
button4.grid(row = 9, column = 1)
button5.grid(row = 4, column = 1)
button6.grid(row = 5, column = 2)
root.mainloop()
Here is a solution using from subprocess import call. All you have to do is replace 'YOUR_FILE_NAME' with... your file name :D
from tkinter import *
from subprocess import call
root=Tk()
root.geometry('200x100')
frame = Frame(root)
frame.pack(pady=20,padx=20)
def open_Menu():
call(["python", "YOUR-FILE-NAME.py"])
btn=Button(frame,text='Open File',command=Open)
btn.pack()
root.mainloop()
What it will look like:
I hope this works for you :D
I was trying to create the scrolled-abled in the frame, where there will be multiple entry lines according to the number of items present. My questions are
1.) My frame Nofy_frame1 with scrollbar is not working (Mentioned the comment #NOT WORKING part) and its position is too close to the entries I did not get any error response. How to solve it?
2.) How to stop/restart the loop while shifting the radio buttons of method 1 and method 2? Since for each click on Add entry button for method 2, the result would be :
Price 1 :
Price 2 :
Price 3 :
Price 4 :
Price 5 :
and then next click on the same Add entry button I am getting
Price 6 :
Price 7 :
Price 8 :
Price 9 :
Price 10 :
instead of the above result
How to resolve it?
I have written the fair code below, Please let me know and clarify my mistakes
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
from tkcalendar import Calendar,DateEntry
from tkinter import messagebox
from tkinter.scrolledtext import ScrolledText
import os
from tkinter import *
import numpy as ny
master0 = tk.Tk()
master0.config(background = "white")
master0.title("Shop Cashier")
master0.geometry("1000x600")
master0.colour_schemes = [{"bg": "#eef1f5", "fg": "black"}, {"bg": "blue", "fg": "white"}]
tabs = ttk.Notebook(master0)
C_1 = 'black'
C_2 = 'white'
TStyler = ttk.Style()
TStyler.configure("TFrame", background=C_2, foreground=C_1, borderwidth=0)
tab1 = ttk.Frame(tabs, style = "TFrame")
tab2 = ttk.Frame(tabs, style = "TFrame")
tab3 = ttk.Frame(tabs, style = "TFrame")
C1 = Canvas(tab1, borderwidth=1, background="white")
C2 = Canvas(tab2, borderwidth=1, background="white")
C2 = Canvas(tab3, borderwidth=1, background="white")
tabs.add(tab1, text ='1')
tabs.add(tab2, text ='2')
tabs.add(tab3, text ='3')
tabs.pack(expand = 1, fill ="both")
#-TAB1
quit_button = tk.Button(tab1, text="Finish", fg="White", bg = "#53c653",padx=10, pady=3,command=master0.destroy)
quit_button.place(x = 450, y= 430)
#-TAB2
InitialInv_r = tk.DoubleVar()
CF_result = tk.DoubleVar()
P_r = tk.DoubleVar()
iiit_r = tk.IntVar()
alent = []
FCI_list = []
VCI_list = []
def addEntry():
if CF_result.get() == 2:
Nofy_frame = Frame(tab2, width = 10, height = 200, bd = 0, background = "#fff080")
Nofy_frame.place(x = 50, y= 150)
Nofy_frame1 = Frame(tab2, width = 270, height = 400, bd = 0, background = "#fff080")
Nofy_frame1.place(x = 50, y= 150)
#============================================================NOT WORKING
Nofy_frame1.pack_propagate(0) # stops frame from shrinking
scroll = Scrollbar(Nofy_frame1)
scroll.pack(side = RIGHT, fill = Y)
#============================================================NOT WORKING
for number in range(iiit_r.get()):
number = len(alent)
#label
ylab = Label(Nofy_frame1, text="Price "+str(number+1)+" :",bg = "#fff080")
ylab.grid(row=number+1, column=0, padx=10, pady=10)
#Entry
ent = Entry(Nofy_frame1, font=('calibri', 11), width = 33)
ent.grid(row=number+1, column=2,padx=10, pady=20)
alent.append( ent )
elif CF_result.get() == 0:
Nofy_frame = Frame(tab2, width = 328, height = 400, bd = 0, background = "#fff080")
Nofy_frame.place(x = 50, y= 150)
Nofy_frame2 = Frame(tab2, width = 270, height = 400, bd = 0, background = "#fff080")
Nofy_frame2.place(x = 50, y= 150)
ylab1 = Label(Nofy_frame2, text="Fixed Price :",bg = "#fff080" )
ylab1.grid(row=1, column=0, padx=2, pady=10)
#Entry
ent = Entry(Nofy_frame2, font=('calibri', 11), width = 30)
ent.grid(row=1, column=2,padx=10, pady=20)
alent.append( ent )
Disct = Label(tab2, text = ' Percentage', bg = "white",padx=3, pady=1,font = ("calibri", 12))
Disct.place(x=400, y=50)
Disctp = Label(tab2, text = '%', bg = "white",padx=3, pady=1,font = ("calibri", 12))
Disctp.place(x=642, y=50)
#Disct_frame = Frame(tab2, width = 200, height = 25, bd = 0, background = "white", highlightcolor = "black", highlightthickness = 1)
#Disct_frame.place(x = 530, y= 50)
Disctv = Entry(tab2,font=('calibri', 12), textvariable= P_r,width = 10, bd=1, bg='#fffce6', justify='left')
Disctv.place(x=560, y=50)
Nofy = Label(tab2, text = 'No. of items :', bg = "white",padx=3, pady=1,font = ("calibri", 12))
Nofy.place(x=700, y=50)
Nofy_frame = Frame(tab2, width = 328, height = 400, bd = 0, background = "#fff080", highlightcolor = "#fff080", highlightthickness = 1)
Nofy_frame.place(x = 50, y= 150)
Nofyv = Entry(tab2,font=('calibri', 12), textvariable= iiit_r, width = 5, bd=1, bg='#fffce6', justify='left')
Nofyv.place(x=800, y=50)
CashFlow = Label(tab2, text = 'Method', bg = "white",padx=3, pady=1,font = ("calibri light", 18))
CashFlow.place(x=50, y=100)
FCF_r = Radiobutton(tab2, variable = CF_result, value = 0, bg = "white")
FCF_r.place(x=180, y=110)
FCF_rr = Label(tab2, text = "method 1", bg = "white",padx=3, pady=1,font = ("calibri light", 12))
FCF_rr.place(x=200, y=108)
vCF_r = Radiobutton(tab2, variable = CF_result, value = 2,bg = "white")
vCF_r.place(x=380, y=110)
vCF_rr = Label(tab2, text = "method 2", bg = "white",padx=3, pady=1,font = ("calibri light", 12))
vCF_rr.place(x=400, y=108)
addEnt = Button(tab2, text='Add entry', fg="White", bg = "#1a1700", command=addEntry)
addEnt.place(x = 400, y= 150)
quit_button = tk.Button(tab2, text="Finish", fg="White", bg = "#53c653",padx=10, pady=3,command=master0.destroy)
quit_button.place(x = 900, y= 530)
master0.mainloop()
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()
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()
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.