Python tkinter printing unexpected newlines - python

Tkinter is adding newlines every 30 seconds:
Unwanted newlines
I'm running this in windows CMD.
I wrote a simple program to test this with a single askopenfilename() call in there.
When I click the browse button, it adds a newline, then after I choose the file and click begin, it adds a newline every 30 seconds while the program is "running":
import tkinter as tk
from tkinter import filedialog
from tkinter.filedialog import askdirectory
import time
def input1():
input1_path = tk.filedialog.askopenfilename()
input1_entry.delete(1, tk.END) # Remove current text in entry
input1_entry.insert(0, input1_path) # Insert the 'path'
#returns file paths for the input files and output directory
def begin():
global inputFileName
inputFileName = input1_entry.get()
master.destroy()
master = tk.Tk()
master.title('Omega NExT Archive Plotter')
one_frame = tk.Frame(master)
two_frame = tk.Frame(master)
line1 = tk.Frame(master, height=1, width=400, bg="grey80", relief='groove')
input1_path = tk.Label(one_frame, text="Archive File Input:")
input1_entry = tk.Entry(one_frame, text="", width=60)
browse1 = tk.Button(one_frame, text="Browse", command=input1)
begin_button = tk.Button(two_frame, text='Begin!', command=begin)
one_frame.pack(side=tk.TOP)
line1.pack(pady=10)
two_frame.pack(side=tk.BOTTOM)
input1_path.pack()
input1_entry.pack()
browse1.pack(pady=10)
begin_button.pack(pady=20, fill=tk.X)
master.mainloop()
time.sleep(1000000)
So I have other guys I work with running this on their computers, and it sounds like the problem is happening on our "managed" computers, but not the "less-than-managed" computers. It sounds like some kind of weird IT issue.

Related

Trying to run .ahk files in tkinter

this is my first time here so if I break some unwritten rules please don't shoot me
I've been trying build an app for editing, reading and opening .ahk files. The last one gives me problems.
this code kind of does what I want except it fires the command immediately after opening the app.
from tkinter import *
from tkinter import filedialog
import os
import threading
root = Tk()
def openfile():
os.system( r'\Users\merijn\PycharmProjects\infoprojectP3\venv\Scripts\ahkScript1.ahk')
def func():
print("hello")
btn1 = Button(text='programma', command=threading.Thread(target=openfile).start())
btn2 = Button(text='ander ding', command=func)
btn1.pack()
btn2.pack()
root.mainloop()
Any help would be much appreciated!
Change the following line (it just assigns the result of threading.Thread(...) to command option):
Button(text="run program1", command=threading.Thread(target=lambda: os.system(r'\Users\merijn\PycharmProjects\infoprojectP3\venv\Scripts\ahkScript1.ahk').start()))
to
Button(text="run program1", command=lambda: threading.Thread(target=lambda: os.system(r'\Users\merijn\PycharmProjects\infoprojectP3\venv\Scripts\ahkScript1.ahk')).start())
or
Button(text="run program1", command=lambda: threading.Thread(target=os.system, args=[r'\Users\merijn\PycharmProjects\infoprojectP3\venv\Scripts\ahkScript1.ahk']).start())
Same for buttons of run program2 and run program3.
Update: based on your updated code, you need to change the following line:
btn1 = Button(text='programma', command=threading.Thread(target=openfile).start())
to
btn1 = Button(text='programma', command=lambda: threading.Thread(target=openfile).start())

askopenfilename is not defined? - Making a browse button in tkinter

The purpose of my code is to create a GUI that has 4 buttons. 2 of them are to open a "browse" window, allowing the user to select a file from a directory. The third button is to allow the user to choose a directory for the final document to be outputted to. The fourth button applies my python code to both files, creating the outputted document.
In attempting to create the "browse" buttons, through many posts here on stackoverflow and on the internet, most solutions include the "askopenfilename" module that is often imported from tkFileDialog. However no matter how I word it, or whatever variations of tkinter modules that i import, I consistently receive the same error messages of "no module name tkfileDialog" or "askopenfilename is not defined".
Am I doing something wrong with my code? Is this a common error found in tkinter with python 3.6? How would one go about creating a browse button that finds a file and adds its path?
Please let me know!
Thanks.
Below is my code:
import os
#from tkFileDialog import *
from tkinter import filedialog
from Tkinter import *
from tkfileDialog import askopenfilename
content = 'apple'
file_path = 'squarebot'
#FUNCTIONS
def browsefunc(): #browse button to search for files
filename = askopenfilename()
infile = open(filename, 'r')
content = infile.read()
pathadd = os.path.dirname(filename)+filename
pathlabel.delete(0, END)
pathlabel.insert(0, pathadd)
return content
def open_file(): #also browse button to search for files - im trying various things to get this to work!
global content
global file_path
#filename = filedialog.askopenfilename(filetypes = (typeName {.txt},))
filename = askopenfilename()
infile = open(filename, 'r')
content = infile.read()
file_path = os.path.dirname(filename)
entry.delete(0, END)
entry.insert(0, file_path)
return content
def process_file(content): #process conversion code
print(content)
def directoryname():
directoryname = filedialog.askdirectory() # pick a folder
#GUI
root = Tk()
root.title('DCLF Converter')
root.geometry("598x600")
mf = Frame(root)
mf.pack()
f1 = Frame(mf, width=600, height=250) #DC file
f1.pack(fill=X)
f2 = Frame(mf, width=600, height=250) #LF file
f2.pack(fill=X)
f3 = Frame(mf, width=600, height=250) #destination folder
f3.pack(fill=X)
f4 = Frame(mf, width=600, height=250) #convert button
f4.pack()
file_path = StringVar
Label(f1,text="Select Your DC File (Only txt files)").grid(row=0, column=0, sticky='e') #DC button
entry = Entry(f1, width=50, textvariable=file_path)
entry.grid(row=0,column=1,padx=2,pady=2,sticky='we',columnspan=25)
Label(f2,text="Select Your LF File (Only csv files)").grid(row=0, column=0, sticky='e') #LF button
entry = Entry(f2, width=50, textvariable=file_path)
entry.grid(row=0,column=1,padx=2,pady=2,sticky='we',columnspan=25)
Label(f3,text="Select Your Destination Folder").grid(row=0, column=0, sticky='e') #destination folder button
entry = Entry(f3, width=50, textvariable=directoryname)
entry.grid(row=0,column=1,padx=2,pady=2,sticky='we',columnspan=25)
Button(f1, text="Browse", command=browsefunc).grid(row=0, column=27, sticky='ew', padx=8, pady=4)#DC button
Button(f2, text="Browse", command=browsefunc).grid(row=0, column=27, sticky='ew', padx=8, pady=4)#LF button
Button(f3, text="Browse", command=browsefunc).grid(row=0, column=27, sticky='ew', padx=8, pady=4)#destination folder button
Button(f4, text="RECONCILE NOW", width=32, command=lambda: process_file(content)).grid(sticky='ew', padx=10, pady=10)#convert button
root.mainloop()
P.S If you have found any other errors in my code please let me know. I am just starting with tkinter, and as such this may be attributed to something completely unrelated!
Much Appreciated
This is what I use in my code so it will work with the Tkinter module in both Python 2 and 3:
try:
import Tkinter as tk
import ttk
from tkFileDialog import askopenfilename
import tkMessageBox
import tkSimpleDialog
from tkSimpleDialog import Dialog
except ModuleNotFoundError: # Python 3
import tkinter as tk
from tkinter import ttk
from tkinter.filedialog import askopenfilename
import tkinter.messagebox as tkMessageBox
import tkinter.simpledialog as tkSimpleDialog
from tkinter.simpledialog import Dialog
You asked to be notified any of other errors and I noticed the way you're using askopenfilename doesn't look right. Specifically, the filetypes keyword argument should be a sequence of two-element tuples containing file type names and patterns that will select what appears in the file listing. So for text files you would use:
filename = askopenfilename(filetypes=[('text files', '*.txt')])
I usually also include a generic pattern to allow easy access to files with other extensions thusly:
filename = askopenfilename(filetypes=[('text files', '*.txt'), ("all files", "*")])
Either way, it's important to remember to check the value returned because it might be the empty string it the user didn't select anything.
The problem was actually that I needed to append askopenfilename() to filedialog as mentioned by Roars in a now deleted comment!(it looks like this --> filedialog.askopenfilename().
The module name is misnamed.
Since the python version is 3.6 you need to use filedialog library. The includes should look something like this:
import os
from tkinter import *
import tkinter.filedialog
or
import os
from tkinter import *
from tkinter import filedialog
You can try this:
from tkinter.filedialog import askopenfilename

I have two .py files. How can I get multi-lined output of one program into tkinter text of another program's GUI?

GUI consists one Run Button which should run the first program as many times user wants & display output in tkinter text.
My code(2nd .py file):
from tkinter import*
from tkinter import ttk
import Random Game
root = Tk()
root.title("Random Game 1.0")
quote = "Long \nRandom \nText \nGenerated \nBy \nRandom Function \nAnd \nControl Structures"
frame = Frame(root)
labelText = StringVar()
label = Label(frame, textvariable=labelText).pack()
button = Button(frame, text="Click to Run").pack()
labelText.set("Random Game 1.0")
Label(root, text ="")
T = Text(root)
frame.pack()
T.pack()
T.insert(END, quote)
root.mainloop()
I want Output of 1st program which is random every time in "tkinter text of another (2nd program) instead of quote lines mentioned in above code.
Output first program to txt file.
Read from that txt file into the tkinter GUI by checking when it was last modified so as to avoid mutex issues.
Therefore:
# Prog 1:
file = open("log.txt", "w")
# code that writes there
# Prog 2:
file = open("log.txt", "r")
# use data to show in the tkinter with its mainloop for example
# in mainloop()...
# .....
if other_prog_has_written_something_new :
data = file.readlines()
useDataInGUI(data)

No input possible after tk

If have this piece of code:
import Tkinter as tk
import tkFileDialog
menu = tk.Tk()
res = tkFileDialog.askopenfilename() # un-/comment this line
label = tk.Label(None, text="abc")
label.grid(row=0, column=0, sticky=tk.W)
entry = tk.Entry(None)
entry.grid(row=0, column=1, sticky=tk.EW)
res = menu.mainloop()
Note: the askopenfilename is just a dummy input. So Just close it to get to the (now blocked) main window of TK.
When I comment the askopenfilename everything works fine. But with the it, I can not enter data in the entry.
This only happens with Windoze environments. The askopenfilename seems to steal the focus for the main TK window. After clicking a totally different window and back again in the TK window, input is possible.
I've seen reports of this before, I think it's a known bug on windows. You need to let mainloop start before you open a dialog.
If you want the dialog to appear when the app first starts up you can use after or after_idle to have it run after mainloop starts up.
For example:
menu = tk.Tk()
...
def on_startup():
res = tkFileDialog.askopenfilename()
menu.after_idle(on_startup)
menu.mainloop()
If you don't want any other GUI code to execute until after the dialog, move all your code except for the creation of the root window and call to mainloop into on_startup or some other function.
For example:
def main(filename):
label = tk.Label(None, text="abc")
label.grid(row=0, column=0, sticky=tk.W)
entry = tk.Entry(None)
entry.grid(row=0, column=1, sticky=tk.EW)
def on_startup():
res = tkFileDialog.askopenfilename()
main(filename)
root = Tk()
root.after_idle(on_startup)
askopenfilenamehas it's own event loop. The programm stops, until you selected a filename, and continues afterwards.

how do i display search results in Python Tkinter window

I am not sure if this question has been asked, but i have looked around and did not find anything specific to my problem. I am trying to build an App to search though all dirs and sub dirs for specific files by there ext(.txt, .mkv, .mp3) mostly these extention will be used (if it matters) I would like the program to display the findings in a text area(text field of sort) to show file name and path.
I have a script that i am working with but i'm not sure if it is the best way to go about it. So my question is how do i binde the existing script to the button widget. i think? there could be more. again still learning.
If there is an easier way(less steps = cleaner code) please "show me the code" Documentation is always helpful but a "hands on" method works best for me. I am still learning Python and Tkinter now. This is not the complete code. i have removed everything that was not working for me so very incomplete.
from tkinter import *
from tkinter import ttk
import os
Root = Tk()
def help!
for dirname, dirnames, filenames in os.walk('/'):
for i in glob.glob(dirname+'/'+search+'*')
print (i)
This part writen for python 2.7 now being writen in 3.x
entry = ttk.Entry(root, text = 'Enter file name')
entry.pack()
button = ttk.Button(root, text = 'Search')
button.pack()
# Text field of sort goes here!
Thanks in advance
UPDATE:
Complete code.
Python 3x (it should be)
from tkinter import *
from tkinter import ttk
from sys import argv
import glob
import os
search_input = argv
#code in question
def find_files():
for dirname, dirnames, filenames in os.walk('/home'):
for i in glob.glob('/*'+searchinput):
listbox.insert(END, search_input)
#Code in question
main = Tk()
main.title("FSX")
main.geometry('640x480')
frame1 = ttk.Frame(main, height=200, width=400)
frame1.pack()
entry = Entry(frame1, width=30)
entry.pack()
button1 = ttk.Button(frame1, text="Search", command=find_files)
button1.pack()
button1.bind ('<ButtonPress>', lambda e: progressbar.start())
button2 = ttk.Button(frame1, text="Quit")
button2.pack()
button2.bind ('<ButtonPress>', lambda e: exit())
progressbar = ttk.Progressbar(frame1, orient = HORIZONTAL, length = 200, mode = 'indeterminate')
progressbar.pack()
#progressbar.start()
frame2 = ttk.Frame(main, height=200, width=400)
frame2.pack()
listbox = Listbox(frame2, height=200, width=400)
listbox.pack(fill=BOTH, expand=YES)
progressbar.stop()
main.mainloop()
this is the complete code. don't mind the progress bar issue.
I modified your example to show the found files in a listbox. In this example I use for log files in /tmp folder. The found files are saved in found_files list and then displayed in listbox.
from tkinter import *
from tkinter import ttk
import glob
import os
search = '*log'
found_files = []
for dirname, dirnames, filenames in os.walk('/tmp'):
for i in glob.glob(dirname+'/'+search+'*'):
print(i)
found_files.append(i)
root = Tk()
root.geometry( "640x480" );
listbox = Listbox(root)
for a_file in found_files:
listbox.insert(END, a_file)
listbox.pack(fill=BOTH, expand=YES)
root.mainloop()
labl = Label(text="{}".format(Result goes here))
labl.pack()
You could display your result like this one. Check for pack() parameters to design your label. What we do here is simple, text parameter of Label function is taking a specific data with format() function.
If your result is from a function, then you have to put it in your function. For example;
def fnk():
a=range(1,100)
lst1=[]
for t in range(6):
while len(lst1)<6:
x=random.choice(a)
if str(x) not in lst1:
lst1.append(str(x))
labl = Label(text="{}".format(" ".join(lst1)), fg="red",font="Times 35 bold")
labl.pack()
bttn = Button(text="Start", command = fnk)
bttn.pack(side=LEFT)
Like a program like this, whenever you click to Start button, you will see different six numbers on your screen in range(1,100). Better you put your results in a list, and put them in format() example above.

Categories