Below is my code, it runs but I'm not sure how to get the "Run text" button to prompt me to open text file in new window, currently a new window appears with a "Quit" button, nothing else.
import tkFileDialog
import Tkinter as tk
from Tkinter import *
import logging
logging.basicConfig(filename= "log_file.txt", filemode = "w", level=logging.DEBUG, format='%(asctime)s %(message)s', datefmt='%d/%m/%Y %I:%M:%S %p')
logging.warning('is when this event was logged.')
class HomeScreen:
def __init__(self, master):
self.master = master
self.frame = tk.Frame(self.master)
self.button1 = tk.Button(self.frame, text = 'Run Text', width = 25, command = self.new_window)
self.button1.pack()
self.frame.pack()
def openFile(self):
openfile = tkFileDialog.askopenfile().read()
text= open(openfile, 'r').read()
T.insert(1.0, openfile)
T = Text(height=10, width=100)
T.pack()
T.insert(END, "Select file to input")
B = Button(root, text="Open", command=openFile)
B.pack()
mainloop()
return
def new_window(self):
self.newWindow = tk.Toplevel(self.master)
self.app = Quit(self.newWindow)
class Quit:
def __init__(self, master):
self.master = master
self.frame = tk.Frame(self.master)
self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25, command = self.close_windows)
self.quitButton.pack()
self.frame.pack()
def close_windows(self):
self.master.destroy()
def main():
root = tk.Tk()
app = HomeScreen(root)
app = Quit(root)
root.mainloop()
if __name__ == '__main__':
main()
I'm sure my code is very messy as I'm just a beginner, some parts may not be needed, any advice would be greatly appreciated.
I've simplified your code a bit, but I've also enhanced it a little. I use askopenfilename rather than askopenfile, so we can get the file name and display it in the titlebar of each Toplevel window containing a Text widget.
import tkFileDialog
import Tkinter as tk
class HomeScreen:
def __init__(self, master):
self.master = master
frame = tk.Frame(master)
frame.pack()
button = tk.Button(frame, text='Show Text', width=25, command=self.open_file)
button.pack()
button = tk.Button(frame, text='Quit', width=25, command=master.destroy)
button.pack()
master.mainloop()
def open_file(self):
filename = tkFileDialog.askopenfilename()
if not filename:
#User cancelled
return
with open(filename) as f:
filedata = f.read()
window = tk.Toplevel(self.master)
window.title(filename)
text = tk.Text(window, height=10, width=100)
text.pack()
text.insert(1.0, filedata)
def main():
root = tk.Tk()
HomeScreen(root)
if __name__ == '__main__':
main()
To display the text file one word at a time you can replace the open_file method with the version below. You'll also need to add the show_word method. I'm not claiming that this is the best way to achieve this effect, but at least it works. :)
def show_word(self, word):
self.text.delete(1.0, tk.END)
self.text.insert(tk.END, word)
def open_file(self):
filename = tkFileDialog.askopenfilename()
if not filename:
#User cancelled
return
with open(filename) as f:
filedata = f.read()
words = filedata.split()
window = tk.Toplevel(self.master)
window.title(filename)
self.text = text = tk.Text(window, height=10, width=100)
text.pack()
delta = 1000 #in millseconds
delay = 0
for word in words:
window.after(delay, lambda word=word: self.show_word(word))
#print word
delay += delta
If you want that "Run text" open's a file dialog change called method:
self.button1 = tk.Button(self.frame, text = 'Run Text', width = 25, command = self.openFile)
Related
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:
I have a custom Entry "self.name_e" on the second window "Demo 2" but anytime I run the code the custom entry only shows up on the first window "Demo 1"...
self.name_e is used to receive the entry on Window 2 "Demo 2"
The AutocompleteEntry is the custom Entry class that is used by windows two
How do I fix this?
import tkinter as tk
#To shorten the code for perfect readability I chose to remove the content of the AutocompleteEntry class
class AutocompleteEntry(Entry):...
class Demo1:
def __init__(self, master):
self.master = master
self.frame = tk.Frame(self.master)
self.button1 = tk.Button(self.frame, text = 'New Window', width = 25, command = self.new_window)
self.master.geometry("1366x768+0+0")
self.button1.pack()
self.frame.pack()
def new_window(self):
self.newWindow = tk.Toplevel(self.master)
self.app = Demo2(self.newWindow)
class Demo2:
def __init__(self, master):
self.master = master
autocompleteList = [ 'Milo tin', 'Shito small' ]
def matches(fieldValue, acListEntry):
pattern = re.compile(re.escape(fieldValue) + '.*', re.IGNORECASE)
return re.match(pattern, acListEntry)
self.frame = tk.Frame(self.master)
self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25, command = self.close_windows)
self.master.geometry("1366x768+0+0")
self.quitButton.pack()
self.frame.pack()
#AutocompleteEntry is a custom Entry which is also a class on it own
self.name_e = AutocompleteEntry(autocompleteList, listboxLength=10, width=20, font=('arial 18 bold'), matchesFunction=matches)
self.name_e.place(x=350, y=150)
def close_windows(self):
self.master.destroy()
def main():
root = tk.Tk()
app = Demo1(root)
root.mainloop()
if __name__ == '__main__':
main()
It runs in IDLE for example and as a .py file, but when I try to get rid of the command line using a .pyw extension the GUI never opens. I'm new with tkinter so I don't know a simple fix, here's my code (sorry that it's a bit sloppy, just doing this as a test):
from pytube import YouTube
import tkinter as tk
import time
from os.path import expanduser
class YTdownloader(tk.Frame):
def __init__(self, main=None):
super().__init__(main)
self.main = main
self.pack()
self.create()
def create(self):
self.text = tk.Label(self, text='Youtube URL').pack(side='top')
url = ''
self.enter = tk.Entry(self, textvariable=url, width=50, justify='center')
self.enter.pack(side='top')
self.done = tk.Button(self, text='Enter', command=self.downloader)
self.done.pack(side='top')
def downloader(self):
try:
vid = YouTube(self.enter.get())
dv = vid.streams.first()
dv.download(expanduser("~") + '\downloads')
self.enter.delete(0, len(self.enter.get()))
self.enter['fg'] = 'green'
self.enter.insert(0, 'Success!')
self.enter['state'] = 'readonly'
screen.after(2000, self.normalize)
except Exception as e:
self.enter.delete(0, len(self.enter.get()))
self.enter['fg'] = 'red'
self.enter.insert(0, 'Video not found!')
self.enter['state'] = 'readonly'
screen.after(2000, self.normalize)
def normalize(self):
self.enter.config(state='normal', fg='black')
self.enter.delete(0, len(self.enter.get()))
screen = tk.Tk()
screen.geometry("325x275")
screen.resizable(width=False, height=False)
screen.configure(bg='white')
img = tk.PhotoImage(file='rpb.png')
tk.Label(screen, image=img, bd=0).pack(side='top')
screen.title("Youtube MP4 Downloader")
inputS = tk.Frame(height=100, bd=1, relief='sunken')
inputS.pack(fill='x', padx=5, pady=5, side='bottom')
yt = YTdownloader(main=inputS)
yt.mainloop()
I want to create a program in Python with Tkinter GUI, and I want it to take string inputs from a user, then I want to do some operations on these strings - in this case, I want to mix parts of two words and get a new word. How can I handle this data entered by a user and use it to receive the result? Below is my code. I couldn't find the answer to this problem and nothing I tried works.
from Tkinter import *
class Window(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master = master
self.init_window()
def init_window(self):
self.master.title("Mix words")
self.pack(fill=BOTH, expand=1)
menu = Menu(self.master)
self.master.config(menu=menu)
entryLbl1 = Label(self, text="Write the first word: ")
entryLbl1.pack()
self.entrytext1 = StringVar()
Entry(self, textvariable=self.entrytext1).pack()
self.buttontext1 = StringVar()
self.buttontext1.set("OK")
Button(self, textvariable=self.buttontext1, command=self.clicked1).pack()
self.label1 = Label(self, text="")
self.label1.pack()
global user_entry1
user_entry1 = self.entrytext1.get()
entryLbl2 = Label(self, text="Write the second word: ")
entryLbl2.pack()
self.entrytext2 = StringVar()
Entry(self, textvariable=self.entrytext2).pack()
self.buttontext2 = StringVar()
self.buttontext2.set("OK")
Button(self, textvariable=self.buttontext2, command=self.clicked2).pack()
self.label2 = Label(self, text="")
self.label2.pack()
global user_entry2
user_entry2 = self.entrytext2.get()
entryLbl3 = Label(self, text="Result: ")
entryLbl3.pack()
self.buttontext3 = StringVar()
self.buttontext3.set("Result")
Button(self, textvariable=self.buttontext1, command=self.clicked3).pack()
self.label3 = Label(self, text="")
self.label3.pack()
def clicked1(self):
input = self.entrytext1.get()
self.label1.configure(text=input)
def clicked2(self):
input = self.entrytext2.get()
self.label2.configure(text=input)
def clicked3(self):
self.user_entry1 = user_entry1
self.user_entry2 = user_entry2
first2a = user_entry1[0:2]
rest_a = user_entry1[2:]
first2b = user_entry2[0:2]
rest_b = user_entry2[2:]
input = first2b + rest_a + " " + first2a + rest_b
self.label3.configure(text=input)
root = Tk()
root.iconbitmap("py.ico")
root.geometry("600x300")
app = Window(root)
root.mainloop()
You need Entry() objects.
The following will show two Entry widgets and a Button.
When the button is pressed, the contents of both of the Entry objects will be printed to the console:
import sys
# Determine if you're running Python 3
is_py_3 = sys.version[0] == '3'
# Import Tkinter for the correct version of Python
if is_py_3:
from tkinter import Button, Entry, Tk
else:
from Tkinter import Button, Entry, Tk
class GUI:
def __init__(self):
# Set up the "Root" or "Parent" of the window.
self.root = Tk()
# Set up two "Entry" widgets.
self.entry1 = Entry(self.root)
self.entry1.insert(0, "Enter something here.")
self.entry2 = Entry(self.root)
self.entry2.insert(0, "and here...")
# Set up a button to handle the event.
self.button = Button(self.root, text="CLICK ME", command=self.onClicked)
self.entry1.pack()
self.entry2.pack()
self.button.pack()
def onClicked(self):
# Print the contents of the entry widgets.
s1 = self.entry1.get()
s2 = self.entry2.get()
print(s1, s2)
app = GUI()
app.root.mainloop()
I am trying to make a GUI for my program but I have changed my code a lot and I saw that GUI misses one frame but it was fine before.
Could anyone help me and tell why a frame with a button does not appear on the bottom?
Whole "button_part" object does not appear.
from tkinter import *
import tkinter as tk
import os
import glob
BOUNDS = ["Last week", "Last 2 weeks", "Last 3 weeks"]
class settings_part:
path_to_copy = 0
def __init__(self, master, update_func):
path_to_copy = StringVar()
settings_frame = Frame(master, background="")
settings_frame.pack(side=TOP, fill=X)
date_bound = StringVar()
date_bound.set(BOUNDS[1])
date_option = OptionMenu(settings_frame, date_bound, *BOUNDS, command=update_func)
date_option.config(background="#732c30")
date_option.config(foreground="white")
date_option.config(bd=0)
date_option.pack(side=LEFT, padx=5, pady=5)
path_to_copy.set("~/Python/usun")
box_with_path = Entry(settings_frame, textvariable=path_to_copy)
box_with_path.pack(side=RIGHT, padx=5, pady=5)
# s = path_to_copy.get()
class songs_part:
def __init__(self, master, root):
self.songs_frame = Frame(master)
self.update_songs(root.list_of_songs)
self.songs_frame.pack()
def update_songs(self, l):
for song in l:
c = Checkbutton(self.songs_frame, text=song[0], variable=song[1])
c.pack()
class button_part:
def __init__(self, master, copyFunc):
self.button_frame = Frame(master)
btn_image = PhotoImage(file="copybtn.png")
self.copy_button = Button(self.button_frame, command=copyFunc, text="Copy",
image=btn_image, highlightthickness=0, bd=0, activebackground="#732c30")
self.copy_button.pack()
class App:
def __init__(self):
root = Tk()
root.title("Copying songs")
root.geometry("500x500")
root.option_add("*Font", "Calibra")
back_image = PhotoImage(file="back.png")
self.window = Label(root, image=back_image)
self.window.pack(fill="both", expand="yes")
self.list_of_songs = list()
self.make_list_of_songs()
self.set_part = settings_part(self.window, self.update_list)
self.son_part = songs_part(self.window, self)
self.but_part = button_part(self.window, self.copy_songs)
root.mainloop()
def make_list_of_songs(self):
owd = os.getcwd()
os.chdir("/home/stanek/Music/usun")
for file in glob.glob("*.mp3"):
self.list_of_songs.append([file, tk.IntVar()])
os.chdir(owd)
def copy_songs(self):
for s in self.list_of_songs:
print(s)
def update_list(self, arg):
print("updating list with songs from " + arg)
self.son_part = songs_part(self.window, self)
if __name__ == '__main__':
App()
You never pack the button frame.