Getting user input in tkinter failing - python

I'm creating a GUI to download files from websites using tkinter.
but i'm getting an unexpected error
The code:
from tkinter import *
from tkinter import ttk
import urllib.request
root = Tk(className='VideoDownloader')
root.geometry("400x200")
root.resizable(width=False, height=False)
Lab = ttk.Label(root, text='Download a file from any site')
Lab.grid(row=0, column=0)
def down():
u = url.get()
n = name.get()
urllib.request.urlretrieve(u, n)
Lab1 = ttk.Label(root, text='Enter file name :')
Lab1.grid(row=1, column=0)
name = ttk.Entry(root,)
name.grid(row=2, column=0)
Lab2 = ttk.Label(root, text='Enter video url :')
Lab2.grid(row=3, column=0)
url = Text(root,)
url.grid(row=4, column=0)
but = ttk.Button(root, text='Download', command=down())
but.grid(row=5, column=0)
root.mainloop()
Creates the error:
Traceback (most recent call last):
File "C:/Users/User/Desktop/test.py", line 30, in <module>
but = ttk.Button(root, text='Download', command=down())
File "C:/Users/User/Desktop/test.py", line 14, in down
u = url.get()
TypeError: get() takes at least 2 positional arguments (1 given)
In my last project i created a GUI to compare numbers and get() do not require a argument

Url is a Text widget, not an Entry widget. If you just want one line, use an Entry widget, and the get() method will work fine.
For a Text widget, which can have multiple lines, use the following to get all input:
url.get("1.0",END)
"1.0" means that the input should be read from the first character of the first line. END is a tkinter constant which is set to the string "end", and means to read until the end of the widget. Infact this will add a newline character to the end of the input, so you should use a customized string:
'end-1c'
meaning one character before the end.

Related

Why doesnt my label refresh with newly entered data in tkinter?

My goal was to refresh a label with its new contents on the click of a button, but when i click the button i get the error message below the code. I understand that it cant access the variable, but i dont understand why. How do i fix it and make the label update when i enter new text in the entry box and click the change button?
Main.py:
import tkinter as tk
from tkinter import *
from tkinter import ttk
from tkinter.messagebox import showinfo # Message Box
from functions import *
root = tk.Tk()
current_title = Label(root, text=homepage.get_title())
current_title.grid(row=1, column=0, sticky=E)
def refresh_title_label():
current_title.destroy()
current_title = Label(root, text=homepage.get_title()) # this homepage.get_title() gets the text from a html file
current_title.grid(row=1, column=1, sticky=W)
def change_title():
x = new_title_input.get()
homepage.change_title(x) # this changes the title in the html file
refresh_title_label()
showinfo('Title Changed')
new_title_label = Label(root, font='Helvetica 15', text='New Title: ' )
new_title_input = Entry(root, background='lightgrey', width=50 )
title_button = ttk.Button(root, text='Change', command=change_title)
new_title_label.grid(row=2, column=0, sticky=E)
new_title_input.grid(row=2, column=1, sticky=W)
title_button.grid(row=2, column=2, sticky=W)
if __name__ == "__main__":
root.mainloop()
functions.py:
# Importing the ssh connection
from ssh_config import *
# This is a class to change the index file
class homepage():
# Gets the website title
def get_title():
data = ssh_command('grep web_title index.html')
data = data[26:]
data = data[:-11]
return data
# changes website title
def change_title(new_title):
current_title = homepage.get_title()
ssh_command(f"sed -i 's/{current_title}/{new_title}/g' index.html")
This is the error message:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\josep\AppData\Local\Programs\Python\Python311\Lib\tkinter\__init__.py", line 1948, in __call__
return self.func(*args)
^^^^^^^^^^^^^^^^
File "c:\Users\josep\Desktop\tkinter-ssh-backend\Untitled-1.py", line 20, in change_title
refresh_title_label()
File "c:\Users\josep\Desktop\tkinter-ssh-backend\Untitled-1.py", line 12, in refresh_title_label
current_title.destroy()
^^^^^^^^^^^^^
UnboundLocalError: cannot access local variable 'current_title' where it is not associated with a value
I tried making the variable global but that didnt work
root = tk.Tk()
global current_title
current_title = Label(root, text=homepage.get_title())
current_title.grid(row=1, column=0, sticky=E)
And i have tested to see if the ssh is working correctly and it is.
In main.py, you cannot put current_title.destroy() before current_title = Label(root). You do this after current_title.grip()
If you want to destroy Label(), you can't do simultaneous in the
refresh_title_label() function.
You can put current_title.destroy() in the change_title() function.
It is up to you to suit your need.
Add current_title.config in the refresh_title_label() function.
I am not using ssh_config. I can do workaround to show.
Snippet:
def refresh_title_label():
current_title.config(text=new_title_input.get())
current_title.grid(row=1, column=0, sticky=E)
def change_title():
x = new_title_input.get()
homepage.change_title(x) # this changes the title in the html file
refresh_title_label()
showinfo('Title Changed')
current_title.destroy()
current_title = Label(root, text=homepage.get_title())
Screenshot:
Screenshot after clicking Change button:
Screenshot destroy the Label:

Python3 Tkinter name error (not defined) on user input

I'm getting the following error:
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py", line 1705, in __call__
return self.func(*args)
File "/Users/XXXXXXXXXXXXX/Desktop/Python/Test Py/TestGUI.py", line 37, in trans1
print(enter_principal)
NameError: name 'enter_principal' is not defined
I'm currently trying to learn python, so I'd be lying if I said I had any idea on what is going wrong. Here is my source code, trying to make a basic compound interest calculator. Getting this error when I'm trying to get an input from the user. Code:
#Importing GUI Module
import tkinter as tk
from tkinter import *
#Creating window
root = tk.Tk()
####Functions#####
#Root screen exit button
def exitroot():
root.destroy()
#principal input
def principal():
#Creating principal window and destroying home window
window = tk.Tk()
exitroot()
#Creating widgets
title_principal = tk.Label(window, text='Please enter your pricipal value: ')
enter_principal = tk.Entry(window)
b1 = tk.Button(window, text='Submit', command=trans1)
title_principal.grid()
enter_principal.grid()
b1.grid()
def trans1():
#temp function for testing purposes
print(enter_principal)
####
#CREATING HOME WINDOW WIDGETS
title_main = tk.Label(root, text="Compound Intrest Calculator", font=("Arial", 20, 'bold'))
start_button = tk.Button(root, text="Start", width='6', height='2', command=principal)
exit_button = tk.Button(root, text="Exit", width='6', height='2', command=exitroot)
credits_main = tk.Label(root, text="M.CXXXXXXXX 2020", font=("Arial", 8))
#PACKING HOME WINDOW WIDGETS VIA GRID
title_main.grid(row='0', columnspan='2')
start_button.grid(row='1', column='0')
exit_button.grid(row='1', column='1')
credits_main.grid(row='2', columnspan='2')
root.mainloop()
Any help is greatly appreciated! I apologise if my code is hard to follow or has blantant errors. I've spent some time looking for a fix but I am really struggling as none have worked.
You need to change
b1 = tk.Button(window, text='Submit', command=trans1)
TO:
b1 = tk.Button(window, text='Submit', command=lambda: trans1(enter_principal.get()))
The reason being is because you need to pass in the value typed into the tk.Entry by using enter_principal.get().
Lambda allows the function to be called only when the button is pressed.(since the command contains parenthesis and so would be called automatically)
Once you've passed this in, you can then pass it into the trans1 function and print it.
def trans1(answer):
# temp function for testing purposes
print(answer)

tkinter: How to avoid this ValueError: could not convert string to float: ''?

from tkinter import *
root = Tk()
entry = Entry(root, width=50)
entry.grid()
entry.grid(row=1,column=0)
def ButtonClick():
userInput = entry.get()
entryLabel = Label(root, text=userInput)
entryLabel.grid()
kilograms = float(userInput)/2.2
answerButton = Button(root, text="Convert!", command=ButtonClick)
answerButton.grid(row=2,column=0)
ButtonClick()
root.mainloop()
I am trying to make a pound to kilogram converter and basically this gives me the error:
Traceback (most recent call last):
File "main.py", line 25, in <module>
ButtonClick()
File "main.py", line 15, in ButtonClick
kilograms = float(userInput)/2.2
ValueError: could not convert string to float: ''
Process finished with exit code 1
The function is being called directly when the code is being executed initially, when the entry box is empty, there is nothing inside of it, so you have to remove that and just call the function from the buttons, and also add try and except if you want to prevent entry of anything other than numbers:
from tkinter import *
root = Tk()
entry = Entry(root, width=50)
entry.grid(row=1, column=0)
def ButtonClick():
userInput = entry.get()
try: # If it is float then do the following
kilograms = float(userInput)/2.2
except ValueError: # If it is not a number, then stop the function
return
entryLabel.config(text=kilograms) # Update the label with the new value
answerButton = Button(root, text="Convert!", command=ButtonClick)
answerButton.grid(row=2, column=0)
entryLabel = Label(root) # Create the label initially, so we can update it later
entryLabel.grid(row=3, column=0)
root.mainloop()

Display tk.Entry text in GUI as tk.Label (Python/Tkinter) Beginner level

I am attempting to learn how to program a GUI application to display text entered in the tk.Entry widget with a tk.Label widget.
code:
import tkinter as tk
window = tk.Tk()
def writelabel():
label = tk.Label(window,text="abc" + entry)
label.pack()
entry = tk.Entry(window)
entry.pack()
button = tk.Button(window,text="Display entry as GUI label", command=writelabel)
button.pack()
window.mainloop()
output:
Traceback (most recent call last):
File "C:\Program Files\Python37\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "D:/Code/Entry to Label.py", line 7, in writelabel
label = tk.Label(window,text="abc" + entry)
TypeError: can only concatenate str (not "Entry") to str
I have already attempted to string the command:
label = tk.Label(str(window,text="abc" + entry))
But I get the same output error as above:
TypeError: can only concatenate str (not "Entry") to str
If I try to also string the entry widget :
entry = tk.Entry(str(window))
I get this error:
AttributeError: 'str' object has no attribute 'tk'
The outcome I desire is for the text that the end user enters in to the tk.entry widget to display as a tk.label widget when the end user clicks on the tk.button widget.
I know the answer is simple, but I just cant see it.
use a StringVar() function
v = StringVar()
set the argument textvariable to the variable v
entry = tk.Entry(window,textvariable=v)
entry.pack()
then inside the label widget you can use the v.get() method to get value from entry widget
label = tk.Label(window,text="abc" + v.get())
you can check the link for more
https://effbot.org/tkinterbook/entry.htm
I worked it out.
I had to string the "entry" variable and include an .get().
IE.
def writelabel():
label = tk.Label(window, text="abc " + str(entry.get()))
label.pack()

Python, problem with tkinter entry function

When i write this in my python code, it display the next error. What can i do to repair it?
filename = tkinter.StringVar()
entry_function = tkinter.Entry(parent, textvariable=filename, bg="black", font=("Hacker", 15, "normal"),fg= "white", width = 18)
tkinter.Entry.insert(0,'keylogger')
tkinter.Entry.pack(default)
Error
Messaggio=insert() missing 1 required positional argument: 'string'
Origine=D:\finale\Homework.py
Analisi dello stack:
File "D:\finale\Homework.py", line 138, in <module>
tkinter.Entry.insert(0,'keylogger')
First define a Entry widget, and then insert a value.
Here is an example:
import tkinter as tk
window = tk.Tk()
ent = tk.Entry(window, width=20)
ent.grid(row=0, column=0)
# insert value
ent.insert(0,'keylogger')
window.mainloop()

Categories

Resources