So, basically I am playing with Tkinter and automatization of web page in Python and the thing that I want to add is the window pop up that allows me to select one of two options (today vs tomorrow in my case).
This is the code:
root = tk.Tk()
def center_window(w=300, h=200):
# get screen width and height
ws = root.winfo_screenwidth()
hs = root.winfo_screenheight()
# calculate position x, y
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
root.geometry('%dx%d+%d+%d' % (w, h, x, y))
root.geometry("400x450")
Label = tk.Label(root, text = "Select Day", font = ("Helvetica", 15))
Label.pack(pady=50, padx=40)
helv15 = tkFont.Font(family = "Helvetica", size = 15)
root.lift()
v = tk.StringVar()
v.set("Today")
tk.Label(root, textvariable = v).pack()
def close_window():
root.destroy()
today = tk.Radiobutton(root, text = "Today", variable = v, value = "Today", font = helv15).pack()
tomorrow = tk.Radiobutton(root, text = "Tomorrow", variable = v, value = "Tomorrow", font = helv15).pack()
submit = tk.Button(root, text = "Submit", command = close_window, font = helv15).pack()
center_window(400, 400)
root.mainloop()
###THERE IS A CODE AFTER THIS POINT
The button that I want to add is "Cancel" button that stops the execution of the whole code and not just the loop of the Tkinter. Thanks!
This should do the trick, just call exit
cancel = tk.Button(root, text = "Cancel", command = exit, font = helv15)
cancel.pack()
The pack method doesn't return anything, so you'll need to split the lines like this if you want to store the widgets
Related
Okay so what I'm trying to figure out is how to control the location of output.
Currently when you run the code a window comes up and allows you to type into a label "manual". with the option to press enter or click the 'submit' button. The typed entry is then put in a new pop-up window every time I.e. Input1(test) and input2(testing) will show up in separate windows. How do I set it so it shows up in the same pop-up window preferably spaced on the y axis so it isn't cluttered. As this is a manual entry there is no telling how many entries will be submitted and it may be possible once so many entries have been entered it will need to move over on the X axis and start again at the top of the Y axis.
I'd also like to know how to pick where the pop-up ends up on the screen I tried using
win.place(x=200, y=50) but the .Toplevel() doesn't have an attribute of .place()
import tkinter as tk
#function that prints the entry
def entry_function(e=None):
name = entry.get()
win = tk.Toplevel()
tk.Label(win, text=name).pack()
win.geometry('100x100')
#Setup for the window
window = tk.Tk()
window.title("Title_Name")
window.geometry("500x500")
window.bind('<Return>', entry_function)
#widgets
label = tk.Label(window, text = "Manual:", bg = "dark grey", fg = "white")
entry = tk.Entry()
button = tk.Button(text = "submit",
command = entry_function)
#widget placement
label.place(x=0,y=20)
entry.place(x=52,y=21)
button.place(x=177, y=18)
window.mainloop()
For displaying the entry on same popup, you can use the below code for entry function
import tkinter as tk
flag = False
win=""
def setflag(event):
global flag
flag = False
#function that prints the entry
def entry_function(e=None):
global flag,win
name = entry.get()
if not flag:
win = tk.Toplevel()
win.geometry('100x100')
win.bind('<Destroy>', setflag)
tk.Label(win, text=name).pack()
flag = True
win.geometry("+%d+%d" % (x + 200, y + 50))
else:
tk.Label(win, text=name).pack()
#Setup for the window
window = tk.Tk()
window.title("Title_Name")
window.geometry("500x500")
window.bind('<Return>', entry_function)
x = window.winfo_x()
y = window.winfo_y()
sh = window.winfo_screenheight()
sw = window.winfo_screenwidth()
x_cord = int((sw/2)-550)
y_cord = int((sh/2)-300)
wh = 550
ww = 1100
window.geometry("{}x{}+{}+{}".format(ww, wh, x_cord, y_cord))
#widgets
label = tk.Label(window, text = "Manual:", bg = "dark grey", fg = "white")
entry = tk.Entry(window)
button = tk.Button(window,text = "submit",
command = entry_function)
#widget placement
label.place(x=0,y=20)
entry.place(x=52,y=21)
button.place(x=177, y=18)
window.mainloop()
You need to create the popup once and add label to it inside entry_function().
You can make the popup hidden initially and show it inside entry_function() and you can specify the position of the popup using geometry().
def entry_function(e=None):
MAX_ROWS = 20 # adjust this value to suit your case
name = entry.get().strip()
if name:
n = len(popup.winfo_children())
tk.Label(popup, text=name).grid(row=n%MAX_ROWS, column=n//MAX_ROWS, sticky='nsew', ipadx=2, ipady=2)
popup.deiconify() # show the popup
window.focus_force() # give focus back to main window
...
# create the popup
popup = tk.Toplevel()
popup.withdraw() # hidden initially
popup.geometry('+100+100') # place the popup to where ever you want
popup.title("Log Window")
popup.protocol('WM_DELETE_WINDOW', popup.withdraw) # hide popup instead of destroying it
...
I need it to store the value of the slider in a variable, say v when the button is clicked. For context, I need this so I can have a slider that sets the starting amount of money for my poker game A level project.
from tkinter import *
root = Tk()
def show_values():
print (w.get()) #would I put it in this function?
canvas = Canvas(root, width = 700, height = 200, bg = "blue")
w = Scale(root,from_=0, to=200,length = 200, orient=HORIZONTAL,bg = "green")
Button(root, text='Show', command=show_values).pack()
w.pack()
canvas.pack()
mainloop()
I'd guess you were setting v in the body of the GUI definition. It needs to be set in the relevant button's command function.
from tkinter import *
root = Tk()
v = 0
def set_value():
global v
v = w.get() # v is set here
def do_print():
print( v ) # v can be read here.
canvas = Canvas(root, width = 700, height = 200, bg = "blue")
w = Scale(root,from_=0, to=200,length = 200, orient=HORIZONTAL,bg = "green")
Button(root, text='Set', command=set_value).pack()
Button(root, text='Print', command = do_print).pack()
w.pack()
canvas.pack()
mainloop()
The 'Set' Button sets the value of v which can be read by clicking the 'Print' Button.
I am trying to create a NoteBook containing Tabs. One the these Tabs contains a Button that when clicked creates an EditText with this line of code
btn1 = ttk.Button(page1, text = "Add Site Code", command=addBox)
The problem is when I click this button it creates the EditText outside the frame like this
I need to show the EditText below the button inside the frame
However this is my code
from tkinter import *
import tkinter.ttk as ttk
import background as background
#------------------------------------
def addBox():
print ("ADD")
ent = Entry(root)
ent.pack()
all_entries.append( ent )
#------------------------------------
all_entries = []
root = Tk()
root.title('Notebook Demo')
# set the configuration of GUI window
w = 600
h = 400
sw = root.winfo_screenwidth()
sh = root.winfo_screenheight()
x = (sw - w) / 2
y = (sh - h) / 2
root.geometry('%dx%d+%d+%d' % (w, h, x, y))
root.config(background = '#A9A9A9')
rows = 0
while rows < 50:
root.rowconfigure(rows, weight=1)
root.columnconfigure(rows, weight=1)
rows += 1
nb = ttk.Notebook(root)
#nb.grid(row=1, column=0, columnspan=50, rowspan=49, sticky='NESW')
page1 = ttk.Frame(nb)
nb.add(page1, text='RDT & On-Air')
nb.pack(expand = 1, fill = "both")
page2 = ttk.Frame(nb)
nb.add(page2, text='Existing Sites')
nb.pack(expand = 1, fill = "both")
page3 = ttk.Frame(nb)
nb.add(page3, text='All Data')
nb.pack(expand = 1, fill = "both")
btn1 = ttk.Button(page1, text = "Add Site Code", command=addBox)
btn1.pack()
root.mainloop()
The problem is that you add the new Entry having root as a parent at line 9:
ent = Entry(root)
You should use the actual frame you want the entry to be in as a parent widget. Substitute root with page1
def addBox():
print ("ADD")
ent = Entry(page1)
ent.pack()
all_entries.append( ent )
I want to create a GUI using python tkinter code, in which it must include: checkbox, file open dialog box, description/details box & submit button
The file open dialog box should get opened only when the checkbox of it is checked in the GUI.
For example, there are 2 checkboxes
1. Soil 2. Weather
Only when the Soil checkbox is checked the file open box should get opened and it has to print the path of the opened file in the console & repeat the same for Weather.
And the details of the selected file should get displayed on the right side of the interface.
At last a submit button needs to be included. After clicking submit button the interface should close.
from tkinter import * #imports
from tkinter import Tk
from tkinter.filedialog import askopenfilename
win = Tk() #create instance
win.title("Spatialization of DSSAT model")
w = 160 # width for the Tk root
h = 100 # height for the Tk root
# get screen width and height
ws = win.winfo_screenwidth() # width of the screen
hs = win.winfo_screenheight() # height of the screen
# calculate x and y coordinates for the Tk root window
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
# set the dimensions of the screen
# and where it is placed
win.geometry('%dx%d+%d+%d' % (w, h, x, y))
def var_states():
print("soil: %d, \nweather:%d" % (var1.get(), var2.get()))
Label(win, text="Select:").grid(row=0, sticky=W)
var1 = IntVar()
Checkbutton(win, text = "soil", variable=var1).grid(row=1, sticky=W)
var2 = IntVar()
Checkbutton(win, text = "weather", variable=var2).grid(row=2, sticky=W)
MyButton1 = Button(win, text="Submit", width=10)
MyButton1.grid(row=10, column=10)
Tk().withdraw()
filename1 = askopenfilename()
print(filename1)
Tk().withdraw()
filename2 = askopenfilename()
print(filename2)
win.mainloop() #start the GUI
You can use command=someFunction for check-buttons and submit-button and then in someFunction() you need to write what you want to be done when that button is clicked.
Try this:
from tkinter import *
from tkinter import Tk
from tkinter.filedialog import askopenfilename
win = Tk()
win.title("Spatialization of DSSAT model")
w = 160
h = 100
ws = win.winfo_screenwidth()
hs = win.winfo_screenheight()
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
win.geometry('%dx%d+%d+%d' % (w, h, x, y))
def forCheckbutton1():
filename1 = askopenfilename()
print(filename1)
def forCheckbutton2():
filename2 = askopenfilename()
print(filename2)
def forMuButton1():
win.destroy()
def var_states():
print("soil: %d, \nweather:%d" % (MyVar1.get(), MyVar2.get()))
MyLabel1 = Label(win, text="Select:")
MyLabel1.grid(row=0, column=0, sticky=W)
MyVar1 = IntVar()
MyVar2 = IntVar()
MyCheckbutton1 = Checkbutton(win, text="soil", variable=MyVar1, command=forCheckbutton1)
MyCheckbutton1.grid(row=1, column=0, sticky=W)
MyCheckbutton2 = Checkbutton(win, text="weather", variable=MyVar2, command=forCheckbutton2)
MyCheckbutton2.grid(row=2, column=0, sticky=W)
MyButton1 = Button(win, text="Submit", width=10, command=forMuButton1)
MyButton1.grid(row=3, column=0)
win.mainloop()
and for displaying information you can add a frame and show your desired information on the frame.
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.