Why global is not working with def function please - python

def global is not working
output:NameError: name 'text2' is not defined
import tkinter as tk
from tkinter import *
from PIL import ImageTk, Image
def getentry():
global entry
global text2
entry = sampiyon.get()
dosya = open("deneme.txt","a")
dosya.write(entry)
dosya = open("sampiyon_listesi.txt","r",encoding="utf-8")
liste = dosya.readline()
global text2
text2 = Label(root, text="Tekrar Deneyin")
if liste == entry:
text1 = Label(root, text="Tebrikler Doğru")
text1.pack()
text2.pack_forget()
else:
text2.pack()
root = Tk()
sampiyon = Entry(root)
print(text2)
root.mainloop()

Add a text2 variable in the global scope
You need to add this line in the global scope.
text2 = None
Here is the code:
from tkinter import *
text2 = None
def getentry():
global entry
entry = sampiyon.get()
dosya = open("deneme.txt", "a")
dosya.write(entry)
dosya = open("sampiyon_listesi.txt", "r", encoding="utf-8")
liste = dosya.readline()
global text2
text2 = Label(root, text="Tekrar Deneyin")
if liste == entry:
text1 = Label(root, text="Tebrikler Doğru")
text1.pack()
text2.pack_forget()
else:
text2.pack()
root = Tk()
sampiyon = Entry(root)
print(text2)
root.mainloop()
Result:

Related

Tkinter link Intvar() with a function and button

As the title suggests, I'm trying to make a counter with IntVar(),so I've tried this.
from tkinter import *
def main():
root = Tk()
root.resizable(FALSE, FALSE)
root.geometry('200x50')
root.title('Home')
#starts here
var = IntVar()
text = 'Count: ' + str(var.get())
b1 = Button(root, text='Test', command=fun)
b1.pack()
l1 = Label(root, text=text)
l1.pack()
mainloop()
def fun():
for i in range(1, 11):
print('test')
main()
But I got confused, I want to make it count the printings and show the value in the label.
Any help would be appreciated.
If you are trying to count the number of times 'test' is printed, you can update the l1 widget with l1['text'] = var after updating. To update, you can fetch the variable of intvar and then add 1 to it. Here's some code:
from tkinter import *
def main():
root = Tk()
root.resizable(FALSE, FALSE)
root.geometry('200x50')
root.title('Home')
#starts here
var = IntVar()
text = 'Count: ' + str(var.get())
b1 = Button(root, text='Test', command=lambda: fun(l1, var))
b1.pack()
l1 = Label(root, text=text)
l1.pack()
mainloop()
def fun(l1, var):
for i in range(1, 11):
print('test')
var.set(var.get()+1)
l1['text'] = 'Count: ' + str(var.get())
main()

Python, I want user to input text file

Hello currently I'm working on a word occurrence counter, I created a gui for it where users can type the words and then press the "count" button and it will count the occurence of each word, however I want to make it so user can instead upload a text file and the word occurrence will count the occurence of each word in the text file instead. Does anyone know how to make the transition? I need to know how to change it from user input words to user upload text files.
import tkinter as tk
from tkinter import *
from collections import Counter
#Functions
def countWords(s):
signos = [',', '.', ';', ':']
cleanstr = ''
for letra in s.lower():
if letra in signos:
cleanstr += ''
else:
cleanstr += letra
strlist = cleanstr.split(' ')
return dict(Counter(strlist))
def button_count():
text = mainWindow.e2.get()
count = countWords(text)
myLabel = Label(root, text=count)
myLabel.pack()
#Graphics
root = tk.Tk()
root.title("Count words")
root.geometry('400x400')
#Background Image Label
bg = PhotoImage(file = "./guibackground.gif")
# Show image using label
label1 = Label( root, image = bg)
label1.place(relx=0.5, rely=0.5, anchor=CENTER)
#Class Window
class Window:
def __init__(self, root):
self.root = root
self.e2 = tk.StringVar()
self.e = tk.Entry(root, textvariable=self.e2, width=35, borderwidth=5)
self.e.pack()
self.button = Button(root, text="Count words", command=button_count)
self.button.pack()
self.exit_button = Button(root, text="Exit", command=root.quit)
self.exit_button.pack()
if __name__ == '__main__':
mainWindow = Window(root)
Use filedialog.askopenfilename method:
import tkinter as tk
from tkinter import filedialog
from collections import Counter
class App(object):
def __init__(self):
self.root = tk.Tk()
self.btn = tk.Button(text='Open File', command=self.open_file)
self.btn.pack()
self.lbl = tk.Label()
self.lbl.pack()
self.root.mainloop()
def open_file(self):
filename = filedialog.askopenfilename(initialdir='/', title='Select file', filetypes=(('text files','*.txt'), ('all files','*.*')))
with open(filename, 'r') as f:
self.lbl.configure(text=f'{Counter(f.read().split())}')
App()
Output:

eror name 'Label1' is not defined

Why doesn't the delete button work?
from tkinter import *
def Diagnosis():
get1 = float(inp.get())
if get1 % 2 == 0:
label1 = Label(windows,font = ('IranNastaliq',20),text = 'عدد زوج است',bg = 'aqua')
label1.pack()
else:
label2 = Label(windows,font = ('IranNastaliq',20),text = 'عدد فرد است ',bg = 'aqua')
label2.pack()
def eraser():
Label1.set('')
Label2.set('')
windows = Tk()
windows.geometry('500x600')
windows.configure(bg ='aqua')
windows.maxsize(500,600)
windows.minsize(400,500)
inp = Entry(windows,font ='IranNastaliq' )
inp.pack()
windows.title("icc-aria gui app")
btn = Button(windows)
btn.configure(text="تایید",font = ('IranNastaliq',14),command = Diagnosis )
btn.pack()
btn1 = Button(text="پاک کن ",font = ('IranNastaliq',14),command = eraser)
btn1.pack()
windows.mainloop()
You are creating the labels inside a function. When the function ends the variables referencing the labels will be garbage collected. Create the labels in global scope to make the references available.
You have misspelled the references in the eraser() function.
To change the contents of a label, use the .config() method.
from tkinter import *
def Diagnosis():
get1 = float(inp.get())
if get1 % 2 == 0:
label1.config(text='عدد زوج است')
else:
label2.config(text='عدد فرد است ')
def eraser():
label1.config(text='')
label2.config(text='')
windows = Tk()
windows.geometry('500x600')
windows.configure(bg ='aqua')
windows.maxsize(500,600)
windows.minsize(400,500)
inp = Entry(windows,font ='IranNastaliq' )
inp.pack()
windows.title("icc-aria gui app")
btn = Button(windows)
btn.configure(text="تایید",font = ('IranNastaliq',14),command = Diagnosis )
btn.pack()
btn1 = Button(text="پاک کن ",font = ('IranNastaliq',14),command = eraser)
btn1.pack()
# Create labels in the global scope
label1 = Label(windows,font = ('IranNastaliq',20),bg = 'aqua')
label1.pack()
label2 = Label(windows,font = ('IranNastaliq',20),bg = 'aqua')
label2.pack()
windows.mainloop()

Get variable value created inside a function

I want to get a variable from a function to use this variable in another function.
Simple example:
from tkinter import *
def test():
intro = "I am "
name = "Phil"
text = intro + name
def printresult():
print(text)
root = Tk()
root.title("Test")
testbutton = Button(root, text="Test", command = test)
printbutton = Button(root, text="print Test", command = printresult)
testbutton.grid(row = 1, column = 0)
printbutton.grid(row = 1, column = 1)
mainloop()
If I press the testbutton and afterwards the printbutton, then I get the error "name 'text' is not defined".
So how am I able to get the text variable from the def test() to use it in the def printresult()?
You need to save the value somewhere well known:
from tkinter import *
def test():
intro = "I am "
name = "Phil"
text = intro + name
test.text = text # save the variable on the function itself
def printresult():
print(test.text)
root = Tk()
root.title("Test")
testbutton = Button(root, text="Test", command = test)
printbutton = Button(root, text="print Test", command = printresult)
testbutton.grid(row = 1, column = 0)
printbutton.grid(row = 1, column = 1)
mainloop()
Since you are using tkinter, I'd use a StringVar to store the result. Using a string var makes it easy for other tkinter widgets to use the value.
from tkinter import *
def test():
intro = "I am "
name = "Phil"
text.set(intro + name)
def printresult():
print(text.get())
root = Tk()
root.title("Test")
text = StringVar()
testbutton = Button(root, text="Test", command = test)
printbutton = Button(root, text="print Test", command = printresult)
testbutton.grid(row = 1, column = 0)
printbutton.grid(row = 1, column = 1)
mainloop()

Removing text files in Python tkinter

I have a problem, and I have no idea why it doesn't work!! :o
I want to remove text files via tkinter, so when the 'user' writes the text file's name and clicks on the button, it will be removed.
from tkinter import *
import tkinter.messagebox
import os, time
root = Tk()
root.geometry('450x320')
root.title('Remove a Text File')
def remove():
if et in os.listdir():
os.remove(et)
tkinter.messagebox.showinfo('Removed!', 'Successfully Removed!')
else:
tkinter.messagebox.showerror('Error!', 'File not found!')
label1 = Label(root, text = 'What to remove ?')
label1.place(x = 70, y = 140)
entry1 = Entry(root)
entry1.place(x = 180, y = 140)
#To fix extension bug
et = entry1.get()
if '.txt' not in et:
et += '.txt'
button1 = Button(root, text = 'Remove', command = remove)
button1.place(x = 210, y = 200)
root.mainloop()
You were getting the value of et before the user had entered anything. Try this:
from tkinter import *
import tkinter.messagebox
import os, time
root = Tk()
root.geometry('450x320')
root.title('Remove a Text File')
def remove():
#To fix extension bug
et = entry1.get()
if '.txt' not in et:
et += '.txt'
if et in os.listdir():
os.remove(et)
tkinter.messagebox.showinfo('Removed!', 'Successfully Removed!')
else:
tkinter.messagebox.showerror('Error!', 'File not found!')
label1 = Label(root, text = 'What to remove ?')
label1.place(x = 70, y = 140)
entry1 = Entry(root)
entry1.place(x = 180, y = 140)
button1 = Button(root, text = 'Remove', command = remove)
button1.place(x = 210, y = 200)
root.mainloop()
Here, check this out:
How to pass arguments to a Button command in Tkinter? (Edit: This is actually not so relevant to the question, but really useful knowledge with TkInter ;)
(In your code's remove function, "et" is not correctly set with the input field's content)
Actually, here's it fixed:
from tkinter import *
import tkinter.messagebox
import os, time
root = Tk()
root.geometry('450x320')
root.title('Remove a Text File')
label1 = Label(root, text = 'What to remove ?')
label1.place(x = 70, y = 140)
entry1 = Entry(root)
entry1.place(x = 180, y = 140)
def remove():
#To fix extension bug
et = entry1.get()
if '.txt' not in et:
et += '.txt'
print(os.listdir())
print(et)
if et in os.listdir():
print("os.remove(",et,")")
tkinter.messagebox.showinfo('Removed!', 'Successfully Removed!')
else:
tkinter.messagebox.showerror('Error!', 'File not found!')
button1 = Button(root, text = 'Remove', command = remove)
button1.place(x = 210, y = 200)
root.mainloop()

Categories