Python, problem with tkinter entry function - python

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()

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()

Getting user input in tkinter failing

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.

Python - function arguments not working

I am making this small program, where the user can input the x and y axis of the screen where they wish to move the mouse to, and how many time they would like to click on that pixel.
My problem is when I try to put the variables into this function, the arguments apparently cannot be converted? The SetCurPos() is the problem, it will take SetCurPos(x,y), but I receive the error:
File "C:\Python27\Scripts\ManipulationTools.py", line 13, in click
SetCursorPos(x,y)
ArgumentError: argument 1: : Don't know how to convert parameter 1
My Code:
from Tkinter import *
import time
import ctypes
#from MoveCursor import click
class ManipulationTools():
##############FUNCTIONS###################################
def click(x,y, numclicks):
SetCursorPos = ctypes.windll.user32.SetCursorPos
mouse_event = ctypes.windll.user32.mouse_event
SetCursorPos(x,y)
E1.DELETE(0, END)
E2.DELETE(0, END)
E3.DELETE(0, END)
for i in xrange(numclicks):
mouse_event(2,0,0,0,0)
mouse_event(4,0,0,0,0)
#############END FUNCTIONS################################
root = Tk()
root.maxsize(width=400, height=400)
root.minsize(width=400, height=400)
root.config(bg="black")
L1 = Label(root,text="Enter the x and y value here:", fg="white", bg="black")
L1.place(x=20, y=20)
Lx = Label(root, text="X:",fg="white",bg="black")
Lx.place(x=170,y=20)
Ly = Label(root, text="Y:",fg="white",bg="black")
Ly.place(x=240,y=20)
Lnum = Label(root, text="Number of Times:",fg="white",bg="black")
Lnum.place(x=150, y=100)
E1 = Entry(root, width=5, bg="grey", )
E1.place(x=190,y=20)
E2 = Entry(root, width=5, bg="grey",)
E2.place(x=260,y=20)
E3 = Entry(root, width=5, bg="grey",)
E3.place(x=260,y=100)
a=IntVar(E1.get())
b=IntVar(E2.get())
c=IntVar(E3.get())
con = Button(root, command=click(a,b,c), text="Confirm", bg="white")
con.place(x=300,y=300)
root.mainloop()
My Traceback error when I click the button to confirm the numbers in the fields entered:
Traceback (most recent call last):
File "C:\Python27\Scripts\ManipulationTools.py", line 6, in
class ManipulationTools():
File "C:\Python27\Scripts\ManipulationTools.py", line 53, in ManipulationTools
con = Button(root, command=click(a,b,c), text="Confirm", bg="white")
File "C:\Python27\Scripts\ManipulationTools.py", line 13, in click
SetCursorPos(x,y)
ArgumentError: argument 1: : Don't know how to convert parameter 1
What you call ####functions#### are actually methods, and hence, the first argument they get is always the reference to the instance of their containing class, which commonly is named self. You can, however, name that parameter like you want to, which is what happened here:
class ManipulationTools():
def click(x,y, numclicks):
x is what elsewhere would be called self, not the first argument that you give when doing something like
tools = ManipulationTools()
tools.click(100,200,1) ## this should actually give you an error -- ManipulationTools.click gets called with 4 arguments (self, 100, 200, 1), but is only defined for 3 (self, y, numclicks)
The right thing to do is:
class ManipulationTools():
def click(self, x,y, numclicks):

Categories

Resources