tkinter overrideredirect stops entry working - python

I would like to create a "Borderless" window in python and my code works without overrideredirect, however when I use this the input is disallowed. I can not click into the Entry box
*This is the code which needs to be figured out, it is currently in a function and there is another 500 lines of code to go with it :D *
newWindow = tkinter.Tk()
w = 300
h = 400
ws = 1024
hs = 768
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
newWindow.configure(background="#2E393D")
newWindow.overrideredirect(True)
frame = tkinter.Frame(newWindow)
name = tkinter.Label(newWindow, background="#1c1c1c", width=2, height=4)
name.pack()
global outputl
global inputl
inputl = tkinter.StringVar()
outputl = tkinter.StringVar()
def nomic(empty):
reply = inputl.get()
inputl.set("")
mainProcess(reply)
if way == "a":
import speech_recognition as sr
r = sr.Recognizer()
with sr.Microphone() as source:
audio = r.listen(source)
try:
reply = r.recognize_google(audio)
mainProcess(reply)
except sr.UnknownValueError:
backCreateFile("I did not understand that !")
else:
inputBox = tkinter.Entry(frame, textvariable=inputl, width=40,foreground="#2E393D", background="white", font=("Ubuntu", 13))
inputBox.bind("<Return>", nomic)
inputBox.pack(fill="x")
outputLabel = tkinter.Label(newWindow, textvariable=outputl)
outputLabel.config( background="#2E393D", foreground="white", wraplength=280, pady=10, font=("Ubuntu", 13))
outputLabel.pack(fill="x")
weatherV = tkinter.StringVar()
weatherV.set("Current Weather - " + status)
weatherLabel = tkinter.Label(newWindow, justify="left", textvariable=weatherV, background="#2E393D", foreground="white", font=("Ubuntu", 13), pady=7).pack(fill="x")
tempV = tkinter.StringVar()
tempV.set("Current Temperature - " + str(ctemp))
tempLabel = tkinter.Label(newWindow, justify="left", textvariable=tempV, background="#2E393D", foreground="white", font=("Ubuntu", 13), pady=7).pack(fill="x")
frame.pack()

I had a similar issue and was able to get around it by using
root.attributes('-fullscreen', True)
This makes the GUI fill the screen completely, creating a 'borderless' window, but still allows for interaction with the entry widgets and setting focus.

I created an account just so i could answer this.
delete the line with your overridedirect statement and replace it with:
root.wm_attributes('-type', 'splash');
^ You are welcome.

Here is minimal code that works on Windows with Python 3.6 and tk 8.6. The popup is in its default position, the upper left corner the screen.
import tkinter as tk
root = tk.Tk()
tag = tk.Label(root, text='Popup entry contents: ')
var = tk.StringVar(root, 'var')
label = tk.Label(root, textvariable=var)
tag.pack(side='left')
label.pack(side='left')
pop = tk.Toplevel(root)
pop.overrideredirect(True)
entry = tk.Entry(pop, textvariable=var)
entry.pack()
#pop.lift() # Needed? for tk 8.5.18+, not for 8.6
Test this on your system, and if it works, figure out what you did differently in your code.

Related

I'm unable to get a string out of tkinter entrybox

import random
import tkinter as tk
frame = tk.Tk()
frame.title("koeweils baldadige encyptor")
frame.geometry('400x200')
printButton = tk.Button(frame,text = "Print", command = lambda: zandkasteel())
printButton.pack()
freek = tk.Text(frame,height = 5, width = 20)
freek.pack()
input_a = freek.get(1.0, "end-1c")
print(input_a)
fruit = 0
fad = input_a[fruit:fruit+1]
print(fad)
schepje = len(input_a.strip("\n"))
print(schepje)
def zandkasteel():
lbl.config(text = "Ingevulde string: "+input_a)
with open("luchtballon.txt", "w") as chocoladeletter:
for i in range(schepje):
n = random.randint()
print(n)
leuk_woord = ord(fad)*n
print(leuk_woord)
chocoladeletter.write(str(leuk_woord))
chocoladeletter.write(str(n))
chocoladeletter.write('\n')
lbl = tk.Label(frame, text = "")
lbl.pack()
frame.mainloop()
I need to get the string that was entered into the text entry field freek. I have tried to assign that string to input_a, but the string doesn't show up.
Right now, input_a doesn't get anything assigned to it and seems to stay blank. I had the same function working before implementing a GUI, so the problem shouldn't lie with the def zandkasteel.
To be honest I really don't know what to try at this point, if you happen to have any insights, please do share and help out this newbie programmer in need.
Here are some simple modifications to your code that shows how to get the string in the Text widget when it's needed — specifically when the zandkasteel() function gets called in response to the user clicking on the Print button.
import random
import tkinter as tk
frame = tk.Tk()
frame.title("koeweils baldadige encyptor")
frame.geometry('400x200')
printButton = tk.Button(frame, text="Print", command=lambda: zandkasteel())
printButton.pack()
freek = tk.Text(frame, height=5, width=20)
freek.pack()
def zandkasteel():
input_a = freek.get(1.0, "end-1c")
print(f'{input_a=}')
fruit = 0
fad = input_a[fruit:fruit+1]
print(f'{fad=}')
schepje = len(input_a.strip("\n"))
print(f'{schepje=}')
lbl.config(text="Ingevulde string: " + input_a)
with open("luchtballon.txt", "w") as chocoladeletter:
for i in range(schepje):
n = random.randint(1, 3)
print(n)
leuk_woord = ord(fad)*n
print(leuk_woord)
chocoladeletter.write(str(leuk_woord))
chocoladeletter.write(str(n))
chocoladeletter.write('\n')
lbl = tk.Label(frame, text="")
lbl.pack()
frame.mainloop()

Only using grid Tkinter but still getting TclError

So I just started using Google Colab and I keep getting this error:
TclError: cannot use geometry manager grid inside . which already has slaves managed by pack
I'm trying to make a GUI window that takes in the information from the user and saves it.
Everything I've read online says that the issue is that I'm using pack() and grid(), but I'm only using grid(). The error starts when I first try to place my labels (sourceLabel).
I'm so confused, any help would be great.
try: # In order to be able to import tkinter for
import tkinter as tk # either in python 2 or in python 3
from tkinter import *
except ImportError:
import Tkinter as tk
from Tkinter import *
#creates window
window = tk.Tk()
window.title("File Information")
window.rowconfigure([0,1], minsize=30)
window.columnconfigure([0, 1, 2, 3], minsize=30)
#this program opens the file with information and adds the new information to it
def saveInfo():
value = path.get()
loc = source.get()
recode = recoding.get()
#change name of file and will this make them see everything
#f = open("./info.txt", "a+")
#f.write("Source Data File Location: " + loc + ", Complete File Path: " + value + ", Is recoding of column names and/or values desired?: " + recode)
#f.flush()
#f.seek(0)
#content = f.read()
#print (content)
finalList = [value,loc,recode]
#f.close()
window.withdraw()
print (finalList)
return finalList
#creates a text label, fg=foreground and bg=background, theyre the locations of colors, width and height are measured by text units which are separate horizonatal and vertical
sourceLabel = tk.Label(
text="Source Data File Location:",
width = 21,
height=2)
#adds text to window
sourceLabel.grid(row=0,column=0)
#creates second label
pathLabel = tk.Label(
text="Complete File Path:",
width = 20,
height=2)
#adds text to window
pathLabel.grid(row=1,column=0)
#creates third label
sourceLabel = tk.Label(
text="Is recoding of column \n names and/or values \n desired:",
width = 20,
height=4)
#adds text to window
sourceLabel.grid(row=2,column=0)
#create dropdown for sources
source = StringVar(window)
source.set("Local") # default value
sourceOption = OptionMenu(window, source, "Local", "Google Drive", "One Drive")
sourceOption.grid(row=0,column=1,sticky="ew")
#adds path entry
path = tk.Entry(fg="black", bg="white", width=35)
#adds path to window
path.grid(row=1,column=1,sticky="ew")
#create dropdown for recoding
recoding = StringVar(window)
recoding.set("Yes") # default value
recodingOption = OptionMenu(window, recoding, "Yes", "No")
recodingOption.grid(row=2,column=1,sticky="new")
#creates the click to save button
button = tk.Button(
text="Click to Save",
width=10,
height=1,
bg="white",
fg="black", command=saveInfo
)
#adds Button to window
button.grid(row=4,column=1,sticky="w")
#runs window
window.mainloop()
window.destroy()
This is a very weird error you had here, I just re-wrote your code using the canvas and pack method, instead of a grid, rows, and columns. Just make sure you are using Python3x Just so none of these weird bugs resurface, hope this helps, you can play around with the x and y values at the bottom, and you can mess with the height and width values at the top when we set the canvas. Happy coding!
from tkinter import *
global path, source, recoding # Global Values so that save_info can get the values
# Creates window
root = Tk()
root.title("File Information")
# Canvas Creates the base layer for the window, so instead of l = Label(text="Test").grid(row=2, column=3)
# We would now do l = Label(text="Test")
# canvas.create_window(20, 30, anchor="nw", window=l)
canvas = Canvas(width=400, height=300)
canvas.pack(fill="both", expand=True)
# Canvas.pack() just finishes creating the canvas.
# This program opens the file with information and adds the new information to it.
def save_info():
global path, source, recoding
value = path.get()
loc = source.get()
recode = recoding.get()
# change name of file and will this make them see everything
# f = open("./info.txt", "a+")
# f.write("Source Data File Location: " + loc + ", Complete File Path: " + value + ", Is recoding of column names and/or values desired?: " + recode)
# f.flush()
# f.seek(0)
# content = f.read()
# print (content)
finalList = [value, loc, recode]
# f.close()
root.withdraw()
print(finalList)
return finalList
sourceLabel = Label(
text="Source Data File Location:",
width=21,
height=2)
pathLabel = Label(
text="Complete File Path:",
width=20,
height=2)
recoding_label = Label(
text="Is recoding of column \n names and/or values \n desired:",
width=20,
height=4)
source = StringVar(root)
source.set("Local") # default value
sourceOption = OptionMenu(root, source, "Local", "Google Drive", "One Drive")
path = Entry(fg="black", bg="white", width=35)
recoding = StringVar(root)
recoding.set("Yes") # default value
recodingOption = OptionMenu(root, recoding, "Yes", "No")
button = Button(
text="Click to Save",
width=10,
height=1,
bg="white",
fg="black", command=save_info
)
# Since we are now using canvas, we must add all the elements using canvas.create_window, the first int is the x value, 2nd is the y
# Just leave anchor always as nw, and windows need to equal the variable of the widget they need to add
canvas.create_window(0, 50, anchor="nw", window=sourceLabel)
canvas.create_window(0, 90, anchor="nw", window=pathLabel)
canvas.create_window(0, 140, anchor="nw", window=recoding_label)
canvas.create_window(150, 50, anchor="nw", window=sourceOption)
canvas.create_window(150, 90, anchor="nw", window=path)
canvas.create_window(150, 140, anchor="nw", window=recodingOption)
canvas.create_window(150, 225, anchor="nw", window=button)
root.mainloop()
# I refactored some of the variables so they would be unique

How do I make a tkinter button destroy itself?

I made this program in Tkinter in python where a small window pops up when the code is run and a start button would pop up and make the window full screen and show the content after. I want to make the button destroy itself after I press it so it makes a fullscreen and removes the button. I am still a beginner and would like the answer to be simple. The solution I am looking for is to maybe destroy the button completely(preferred) or move it way out of sight in the fullscreen window. Here is the code:
import Tkinter as w
from Tkinter import *
w = Tk()
w.geometry("150x50+680+350")
def w1():
w.attributes("-fullscreen", True)
l1 = Label(w, text = "Loaded!", height = 6, width = 8).pack()
global b1
b1.place(x = -10000, y = -10000)
b1 = Button(w, text = "Start", height = 3, width = 20, command = w1).place(x = 0, y = 10)
b2 = Button(w, text = "Exit", command = w.destroy).place(x = 1506, y = 0)
w.mainloop()
As you can see I want to make button one destroy itself.
Try this:
import tkinter as tk # Use `import Tkinter as tk` for Python 2
root = tk.Tk()
root.geometry("150x50+680+350")
def function():
global button_start
root.attributes("-fullscreen", True)
label = tk.Label(root, text="Loaded!", height=6, width=8)
label.pack()
button_start.place_forget() # You can also use `button_start.destroy()`
button_start = tk.Button(root, text="Start", height=3, width=20, command=function)
button_start.place(x = 0, y = 10)
button_exit = tk.Button(root, text="Exit", command=root.destroy)
button_exit.place(x=1506, y=0)
root.mainloop()
PS: Please read this.
Try:
b1.place_forget()
This will essentially "forget" about the button and hide it from view.
Edit:
If you are getting the error that b1 is None try:
b1 = Button(w, text = "Start", height = 3, width = 20, command = w1)
b1.place(x = 0, y = 10)
You need to add the b1.place() option at the bottom for this to work

"Resetting" a tkinter window

I'm currently trying to create a command centre to integrate with one of my other python programs, however, I am quite new to Tkinter, and as such, I was wondering if there was a way to "reset" a window that has widgets in it so that I can have a clean window to place new widgets in, without storing any data or using system resources. Here is the code I currently have:
import tkinter
tk = tkinter
window = tk.Tk()
def login():
window.title("SCC: Login")
header = tk.Label(window, text = "Please Login").pack()
frame = tkinter.Label(window, text = "Username").pack()
frame = tkinter.Entry(window).pack()
frame = tkinter.Label(window, text = "Password").pack()
frame = tkinter.Entry(window).pack()
frame = tkinter.Checkbutton(window, text = "Keep Me Logged In").pack()
frame = tkinter.Button(window, text = "Login", command = mainMenu).pack()
window.mainloop()
def mainMenu():
()
window.title("SCC")
tk.Label(window, text = "Welcome to the Sentinel Command Center").pack()
tk.Button(window, text = "Network Utilities", fg = "orange").pack()
tk.Button(window, text = "Image Recognition", fg = "orange").pack()
tk.Button(window, text = "Voice Recognition", fg = "orange").pack()
window.mainloop()
login()
also as a side note i am fully aware the current password form is non functional, its just a placeholder for now until i find a better method of authorization for the code.
Arguably, the easiest way to reset it is to put all of your widgets inside a frame, and then create a function that creates the frame. Then, to do a reset you can destroy the current frame and call your function to recreate it.
Update:
I found a functional if a convoluted method to doing this, just by creating separate windows, then withdrawing the login window once the main menu has been called. Here is the code if you want to use it:
mainWindow = tk.Tk()
loginWindow = tk.Tk()
version = ("v0.1")
def centerwindowLogin(width=300, height=200):
screen_width = loginWindow.winfo_screenwidth()
screen_height = loginWindow.winfo_screenheight()
x = (screen_width/2) - (width/2)
y = (screen_height/2) - (height/2)
loginWindow.geometry('%dx%d+%d+%d' % (width, height, x, y))
def centerwindowMain(width=300, height=200):
screen_width = mainWindow.winfo_screenwidth()
screen_height = mainWindow.winfo_screenheight()
x = (screen_width/2) - (width/2)
y = (screen_height/2) - (height/2)
mainWindow.geometry('%dx%d+%d+%d' % (width, height, x, y))
def login():
loginWindow.title("SCC v0.1")
header = tk.Label(loginWindow, text = "Please Login").pack()
tk.Label(loginWindow, text = "Username").pack()
tk.Entry(loginWindow).pack()
tk.Label(loginWindow, text = "Password").pack()
tk.Entry(loginWindow).pack()
tk.Checkbutton(loginWindow, text = "Keep Me Logged In").pack()
tk.Button(loginWindow, text = "Login", command = mainMenu).pack()
centerwindowLogin(300, 175)
loginWindow.mainloop()
def mainMenu():
loginWindow.withdraw()
mainWindow.title("SCC v0.1")
tk.Label(mainWindow, text = "Welcome to the Sentinel Command Center").pack()
tk.Button(mainWindow, text = "Network Utilities", fg = "orange").pack()
tk.Button(mainWindow, text = "Image Recognition", fg = "orange").pack()
tk.Button(mainWindow, text = "Voice Recognition", fg = "orange").pack()
centerwindowMain(500, 400)
mainWindow.mainloop()
login()
This function can be used to remove all existing widgets:
def wempty(w):
for w in w.winfo_children():
w.destroy()

How would I create a reset button for my program relating with the following code?

I am trying to add a reset button but I can't seem to get it to work. I created a main in order to refer back to it when the button is pressed but no luck. Any ideas?
import sys
from tkinter import *
import math
def main():
def closeWin():
myGui.destroy() #Close Window Function
def kiloFunc():
myText = kiloMent.get() #Kilometers to Miles Fuction
convert = 0.62
miles = myText * convert
finalKilo = Label(text = miles,fg='red',justify='center').place(x=200,y=80)
def mileFunc():
myText2 = mileMent.get() #Miles to Kilometers Function
convertTwo = myText2 // 0.62
finalMile = Label(text = convertTwo, fg = 'red',justify='center').place(x=200,y=170)
myGui = Tk()
kiloMent = IntVar()
mileMent = IntVar()
myGui.title("Distance Converter")
myGui.geometry("450x200+500+200")
myLabel = Label(text="Welcome! Please enter your value then choose your option:",fg="blue",justify='center')
myLabel.pack()
kiloEntry = Entry(myGui, textvariable = kiloMent,justify='center').pack()
kilo2milesButton = Button(text = "Kilometers to Miles!", command = kiloFunc).pack()
mileEntry = Entry(myGui, textvariable = mileMent,justify='center').place(x=130,y=105)
miles2kiloButton = Button(text = "Miles to Kilometers!", command = mileFunc).place(x=150,y=135)
reset = Button(text = "Reset Values!", command = main).place(x=10,y=165)
quit = Button(text="Quit", command = closeWin).place(x=385,y=165)
myGui.mainloop()
main()
By calling main() again, you are simply creating another instance of the GUI. What you should do instead is (if I understand correctly), reset the values of the currently existing GUI. You can use the set() method of the GUI objects.
Does
def reset_values():
kiloMent.set(0)
mileMent.set(0)
reset = Button(text="Reset Values!", command=reset_values).place(x=10, y=165)
do the trick?
Looking at your code more thoroughly, however, there are some other problems there, as well. To start with, I would suggest not creating a Label everytime the user tries to convert a value.
This code should work:
from tkinter import *
def main():
def closeWin():
myGui.destroy() # Close Window Function
def kiloFunc():
finalKilo.set(kiloMent.get() * 0.62) # Kilometers to Miles Fuction
def mileFunc():
finalMile.set(mileMent.get() // 0.62) # Miles to Kilometers Function
def clearFunc():
kiloMent.set("0")
mileMent.set("0")
finalKilo.set("")
finalMile.set("")
myGui = Tk()
kiloMent = IntVar()
mileMent = IntVar()
finalKilo = StringVar()
finalMile = StringVar()
myGui.title("Distance Converter")
myGui.geometry("450x200+500+200")
myLabel = Label(text="Welcome! Please enter your value then choose your option:", fg="blue", justify='center')
myLabel.pack()
kiloEntry = Entry(myGui, textvariable=kiloMent, justify='center')
kiloEntry.pack()
kilo2milesButton = Button(text="Kilometers to Miles!", command=kiloFunc)
kilo2milesButton.pack()
mileEntry = Entry(myGui, textvariable=mileMent, justify='center')
mileEntry.place(x=130, y=105)
miles2kiloButton = Button(text="Miles to Kilometers!", command=mileFunc)
miles2kiloButton.place(x=150, y=135)
kiloLabel = Label(textvariable=finalKilo, fg='red', justify='center')
kiloLabel.place(x=200, y=80)
mileLabel = Label(textvariable=finalMile, fg='red', justify='center')
mileLabel.place(x=200, y=170)
reset = Button(text="Reset Values!", command=clearFunc)
reset.place(x=10, y=165)
quit = Button(text="Quit", command=closeWin)
quit.place(x=385, y=165)
myGui.mainloop()
main()
A few notes about your original code besides the ones that Chuck mentioned:
The math and sys imports were unused.
You were setting variables equal to widget.pack() and widget.place(), which are functions that return None.

Categories