I've been tying to set text to a label but i get this error despite doing the same thing above it with no error, "AttributeError: 'Label' object has no attribute 'set'"
Here is my code and all help is of course appreciated :)
:
#creating the labels
text = StringVar()
text.set("-------")
plate1 = Label(DDFrame1,textvariable = text)
plate1.grid(row=0,column=1)
text1 = StringVar()
text1.set("-------")
owner1 = Label(DDFrame1,textvariable = text1)
owner1.grid(row=1,column=1)
text2 = StringVar()
text2.set("-------")
flags1 = Label(DDFrame1,textvariable = text2)
flags1.grid(row=2,column=1)
def changeText2():
import random
name = ["Vickie Vanfleet","Marcellus Amaker","Cyndi Beale","Roni Foti","Carolyn Sealey",
"Lynda Ansell","Tomiko Kimbrell","Elfreda Bontrager","Melynda Mayberry",
"Precious Nolan","Carl Harm","Trevor Olsen","Anamaria Christianson","Jonna Wagnon",
"Alvina Flock","Sima Lablan","Talisha Fripp","Janey Smedley","Kelly Delpozo",
"Shanice Folse","Sharice Wissing","Darlena Steele","Darlena Steele","Chana Tews",
"Agueda Struble","Harriette Pacifico","Brandon Ellisor","Garry Foushee",
"Telma Kellett","Randa Wojciechowski","Claire Snow","Willa Bankes","Arnold Fall",
"Salome Ridings","Venus Tuner","Willetta Hendriks","Leana Straus"]
name_outcome = random.choice(name)
text1.set(name_outcome)
def changeText3():
import random
reports = ["rep1","rep2","rep3"]
report_outcome = random.choice(reports)
text2.set(report_outcome) #this is the line the error is referencing
Replace text1.set(name_outcome) with text1.configure(text=name_outcome). Same for text2 with report_outcome.
The Label method has no .set() method, you may be confusing it with the StringVar class which does. To work with something like that you would instantiate the label using the textvariable= attribute instead:
text = tkinter.StringVar()
tkinter.Label(root, textvariable=text).pack()
# henceforth usages of text.set("some string") will update the label
Related
Long ago i watched a tutorial on how to encrypt files(of any kind) with a key/password
The original code just makes the process in the terminal, but i wanted to make it into an application using tkinter as my GUI, i've come to a problem my small brain can't solve
The original video: https://www.youtube.com/watch?v=HHlInKhVz3s
This is the error i get: TypeError: Encrypt() missing 2 required positional arguments: 'WhichFile' and 'KeyInput'
This is my code:
from tkinter.filedialog import askopenfilename
import time
root = Tk()
root.title=("Tkinter Calculator")
root.geometry("500x500")
#title
WindowTitle = Label(root, text="Choose Action", font=("Arial", 15))
WindowTitle.place(x=250, y=10,anchor="center")
### The functions
#Encrypt
def Encrypt(WhichFile, KeyInput):
file = open(WhichFile, "rb")
data = file.read()
file.close()
data = bytearray(data)
for index, value in enumerate(data):
data[index] = value ^ KeyInput
file = open("CC-" + WhichFile, "wb")
file.write(data)
file.close()
#Decrypt
def Decrypt(WhichFile, KeyInput):
file = open(WhichFile, "rb")
data = file.read()
file.close()
data = bytearray(data)
for index, value in enumerate(data):
data[index] = value ^ KeyInput
file = open(WhichFile, "wb")
file.write(data)
file.close()
#Step1 - Write the name of the file(Needs to be in the same folder(Also include ext.))
WhichFile = Entry(root, width = 20)
WhichFile.place(x=100, y=150)
WhichFile.insert(0, "Enter File name with extension")
#Step2 - Ask for a key/password
KeyInput = Entry(root, width = 20)
KeyInput.place(x=100, y=250)
KeyInput.insert(0, "Enter a key: ")
#Button for encrypt
Encryptbtn = Button(root, text="Encrypt", highlightbackground='#3E4149', command=Encrypt)
Encryptbtn.place(x=100, y=350)
#Button for decrypt
Decryptbtn = Button(root, text="Decrypt", highlightbackground='#3E4149', command=Decrypt)
Decryptbtn.place(x=200, y=350)
root.mainloop()
So the error occurs in this line:
Encryptbtn = Button(root, text="Encrypt", highlightbackground='#3E4149', command=Encrypt)
Passing a function with arguments to Button's "command"
You have to pass the arguments to the function Encrypt() which demands args "WhichFile" and "KeyInput".
You can pass arguments in Button declaration by using lambda keyword:
Button(root, text="Encrypt", highlightbackground='#3E4149', command=lambda:Encrypt(file,input))
It will take the values of "file" and "input" just when you click on the button, remember it cause sometime it is not that what you actually want (e.g. Python Tkinter button callback).
If you want the arguments to be "remembered" as they was at moment of creating button, use currying
(What is 'Currying'? ,
More about "lambda").
So, for first you have to pass arguments to that function. As I can see, you slightly don't understand how it works, cause you're trying to use the arguments in declaration of a funtion like they were a global variables of something (def Encrypt(WhichFile, KeyInput) and then as an "assignment" WhichFile = Entry(...)) but it doesn't work like that, arguments that are passed to function are specified in function's call, e.g. foo(argument1,argument2), not at the moment of defining it.
Getting text from Entry :
You have to know, that WhichFile = Entry(root, width = 20) is not assigning the value of Entry to WhichFile variable, but the Entry itself (check it by using print(WhichFile)). I propose changing the name of that variable for e.g. "user_input_file" or sth.
If you want to get the text typed in the Entry use user_input_file.get().
Excatly the same thing with KeyInput Entry.
Next, you have to create a variable that will point to that value (python varaibles are pointers), and assign it in that function in a way I mentioned before (with that lambda:).
Just write it as a global variable, for example:
WhichFile = user_input_file.get()
KeyInput = user_input_key.get()
Of course after declaring user_input_file and user_input_key.
I think that'll solve ur problem, feel free to ask 'bout more.
The code displayed below is giving me a ValueError, explaining I need a title or pagid specified. I have checked the code over and over and do not see a problem. Please let me know if you have any idea what I am doing wrong.
This code is meant to give me information about most key words I enter. If I want Jeff Bezos, information will be printed to the console.
# Imports
import wikipedia
from tkinter import *
import time
# Code
def Application():
# Definitions
def Research():
# Defines Entry
Result = wikipedia.summary(Term)
print(Result)
# Window Specifications
root = Tk()
root.geometry('900x700')
root.title('Wikipedia Research')
# Window Contents
Title = Label(root, text = 'Wikipedia Research Tool', font = ('Arial', 25)).place(y = 10, x = 250)
Directions = Label(root, text = 'Enter a Term Below', font = ('Arial, 15')).place(y = 210, x = 345)
Term = Entry(root, font = ('Arial, 15')).place(y = 250, x = 325)
Run = Button(root, font = ('Arial, 15'), text = 'Go', command = Research).place(y = 300, x = 415)
# Mainloop
root.mainloop()
# Run Application
Application()
You're passing Term to wikipedia.summary(). The error is coming from when summary() creates a page (code). This error happens when there is no valid title or page ID being passed to the page (code). This is happening in your case because you're passing Term straight to summary(), without first converting it to a string. Additionally, Term is a NoneType object, because you're actually setting it to the result of place(). You have to store Term when you create the Entry(), and then apply the place operation to it, in order to be able to keep a reference to it (see here for why):
Term = Entry(root, font = ('Arial, 15'))
Term.place(y = 250, x = 325)
Then, you can get the text value via:
Result = wikipedia.summary(Term.get())
I'm currently writing a manga reader and viewer program using the tkinter library in python for a gui, Im trying to make it so it lists the titles currently, and as I do this I realize its overlapping them, ive searched far and wide but wasnt able to find a good procedure to lets say "remove/forget" them on the new button press.
My code is listed below:
import json, webbrowser, requests
import tkinter as tk
from tkinter.ttk import *
from urllib import *
import urlopen
from urllib.request import *
import os
os.system("chcp 65001")
app = tk.Tk()
def get_button():
mid = entry.get()
if mid == "soap":
mid = "176758"
url = f"https://somewebsite/api/gallery/{mid}"
#label and pack for manga id
mangaid = tk.Label(text=f"ID : {mid}")
mangaid.grid(column=0, row=4, columnspan=2,)
#prints the url
print(url)
#open url data
uf = requests.request(method="get",url=url)
j_result = uf.json()
title = j_result['title']
j_title = title['japanese']
e_title = title['english']
#shows the title text
mangaide = tk.Label(text=f"English Title : {e_title}")
mangaidj = tk.Label(text=f"Japanese Title : {j_title}")
mangaide.grid(column=0, row=5, columnspan=2,)
mangaidj.grid(column=0, row=6, columnspan=2,)
def on_open():
mid = entry.get()
if mid == "soap":
mid = "176758"
URL = f"https://somewebsite.net/g/{mid}/"
#opens url
webbrowser.open(URL, new=2)
print(URL)
enterid = tk.Label(text="Enter ID or Name")
entry = tk.Entry()
button = tk.Button(text="Get", command=get_button)
button2 = tk.Button(text="Open", command=on_open)
enterid.grid(column=0, columnspan=2, pady=(10))
entry.grid(column=0, columnspan=2, padx=(50))
button.grid(row=3, column=0, pady=(10))
button2.grid(row=3,column=1)
app.mainloop()
If you look at lines 29-32 Im assigning a label and placing it on the grid, although when I press the button again, to get new data, it proceeds to do the following:
1st Data Grab
2nd Data Grab
In the first one you can see that it worked perfectly, but in the 2nd grab you can see that it took the previous answers and overlayed them behind, so in gist m trying to figure out a way to fix this, my main goal is to find a way to remove the overlayed text.
Im sorry if this isnt specific enough, if it isnt please contact me on discord (Ganoosh#4020) or through stack overflow comments.
Create empty Labels above app.mainloop() like this:
mangaide = tk.Label()
mangaidj = tk.Label()
mangaide.grid(column=0, row=5, columnspan=2,)
mangaidj.grid(column=0, row=6, columnspan=2,)
and put text on them inside get_button() function with the use of global keyword. Modify your get_button() function like this:
def get_button():
global mangaidj, mangaide # Using global keyword to access those Labels
mid = entry.get()
if mid == "soap":
mid = "176758"
url = f"https://somewebsite/api/gallery/{mid}"
#label and pack for manga id
mangaid = tk.Label(text=f"ID : {mid}")
mangaid.grid(column=0, row=4, columnspan=2,)
#prints the url
print(url)
#open url data
uf = requests.request(method="get",url=url)
j_result = uf.json()
title = j_result['title']
j_title = title['japanese']
e_title = title['english']
#shows the title text
mangaide.config(text=f"English Title : {e_title}") # These lines will
mangaidj.config(text=f"Japanese Title : {j_title}") # update the text each time
Hpoe this helps :)
I have a dictionary that contains tkinter labels, but below I'm only including the first part of the dictionary
When I use variables, in the example below I get no errors.
from tkinter import *
root = Tk()
dic = {'response1':Label(root, bg='white')}
lbl = dic['response1']
lbl.config(text='Hey')
lbl.pack()
mainloop()
But when I do it without variables, like this
from tkinter import *
root = Tk()
dic = {'response1':Label(root, bg='white')}
dic['response1'].config(text='Hey').pack()
mainloop()
I get this error
AttributeError: 'NoneType' object has no attribute 'pack'
and since that, I need to declare a variable for each label in the dictionary so that I can avoid this error. So I'm asking how to declare a variable for each item in dictionary, where the key is the variable name. So response1 = Label(root, bg='white') and so on for each item in the dictionary.
You don't need to use variables, your error actually comes from you trying to use the results of .config, to .pack.
Try the following:
from tkinter import *
root = Tk()
dic = {'response1':Label(root, bg='white')}
dic['response1'].config(text='Hey')
dic['response1'].pack()
mainloop()
I'm wondering if anyone can give me a quick simple fix for my issue.
I'm trying to make a program (as a gcse mock) that will obtain the position of words in a sentence.
I have the sentence bit working great in the text however I want to go above and beyond to get the highest possible marks so I'm creating it again with a gui!
So far I have the following code and it's not working correctly, it's not updating the 'sentence' variable and I'm looking for a simple way around fixing this Instead of updating. I get some random number which I'm not sure where it has come from. Any help will be much appreciated. :)
#MY CODE:
#GCSE MOCK TASK WITH GUI
import tkinter
from tkinter import *
sentence = ("Default")
window = tkinter.Tk()
window.resizable(width=FALSE, height=FALSE)
window.title("Sentence")
window.geometry("400x300")
#Add custom logo here later on
def findword():
print ("")
sentencetext = tkinter.Label(window, text="Enter Sentence: ")
sentence = tkinter.Entry(window)
sentencebutton = tkinter.Button(text="Submit")
findword = tkinter.Label(window, text="Enter Word To Find: ")
wordtofind = tkinter.Entry(window)
findwordbutton = tkinter.Button(text="Find!", command = findword)
usersentence = sentence.get()
usersentence = tkinter.Label(window,text=sentence)
shape = Canvas (bg="grey", cursor="arrow", width="400", height="8")
shape2 = Canvas (bg="grey", cursor="arrow", width="400", height="8")
#Packing & Ordering Modules
sentencetext.pack()
sentence.pack()
sentencebutton.pack()
shape.pack()
findword.pack()
wordtofind.pack()
findwordbutton.pack()
usersentence.pack()
shape2.pack()
window.mainloop()
Currently your sentence's 'submit' button doesn't actually have a command bound, and the two 'sentence' references are likely to conflict:
sentencebutton = tkinter.Button(text="Submit")
sentence = ("Default")
sentence = tkinter.Entry(window)
I can see that what you've tried to do is set it so that the variable sentence changes from "Default" to whatever one enters in the Entry window - this will not work, all you've done is set it so that sentence becomes the entry widget itself, not whatever is entered.
I would recommend creating a function called something like 'update_sentence', and rename your initial 'sentence' variable to distinguish it from the label:
var_sentence = "default"
def update_sentence:
var_sentence = sentence.get()
And then change your button so it has a command, like so:
sentencebutton = tkinter.Button(text="Submit", command = update_sentence)
Hope this helps!