I want to be able to control the default restored size of my windows when click the restore button of the window itself. Right now whenever I click the restore button it stays with the maximized size which is the screen resolution but it just moves to the right a little bit. I want in a way that I can set up a default size before dragging it smaller or bigger depending on the desired size. I attached my code for reference
from tkinter import *
from tkinter.filedialog import *
from pathlib import Path
from win32api import GetSystemMetrics
filename = None
file_path = None
files = [
('All Files', '*.*'),
('Python Files', '*.py'),
('Text Document', '*.txt')
]
def newFile():
global filename
filename = "untitled"
text.delete(0.0, END)
def saveFile():
global filename
t = text.get(0.0, END)
try:
f = open(file_path, mode='w')
f.write(t)
f.close()
except:
saveAs()
def saveAs():
f = asksaveasfile(mode='w', initialdir="C:\\Users\\charl/Documents", filetypes=files, defaultextension=".txt")
t = text.get(0.0, END)
f.write(t)
# except:
# f.showerror(title="Oops!", message="Unable to save file...")
def openFile():
global filename, file_path
f = askopenfile(mode='r')
filename = Path(f.name).stem
file_path = f.name
t = f.read()
text.delete(0.0, END)
text.insert(0.0, t)
f.close()
root = Tk()
root.title("My Python Text Editor")
root.state('zoomed')
root.minsize(width=400, height=400)
root.maxsize(width=GetSystemMetrics(0), height=GetSystemMetrics(1))
text = Text(root, width=400, height=400)
text.pack(fill="both", expand=True)
menubar = Menu(root)
file = Menu(root)
filemenu = Menu(menubar, tearoff=False)
filemenu.add_command(label="New", command=newFile)
filemenu.add_command(label="Open", command=openFile)
filemenu.add_command(label="Save", command=saveFile)
filemenu.add_command(label="Save As...", command=saveAs)
filemenu.add_separator()
filemenu.add_command(label="Quit", command=root.quit())
menubar.add_cascade(label="File", menu=filemenu)
root.config(menu=menubar)
root.mainloop()
It is because the text box is too large. Try removing the width and height options from text = Text(...) like below:
text = Text(root)
Related
I'm making a simple text editor and whenever I try to save a file it always gives me this error.
I'm saving it as a normal text file and I cant find the reason why this is happening. I've tried saving it to a different location, made some debugging attempts. Nothing. Could someone help me out?
Code:
from tkinter import*
from tkinter import filedialog
from tkinter import font
root = Tk()
root.title("NewNotepad")
root.geometry("1200x660")
def new_file():
my_text.delete("1.0", END)
root.title('New File')
status_bar.config(text="New File")
def open_file():
my_text.delete("1.0", END)
text_file = filedialog.askopenfilename(title="Open File", filetypes=(("Text Files", "*txt"), ("HTML Files", "*html")))
name = text_file
status_bar.config(text=name)
text_file = open(text_file, 'r')
stuff = text_file.read()
my_text.insert(END, stuff)
text_file.close()
def save_as_file():
text_file = filedialog.asksaveasfilename(defaultextension=".*", title="Save File", initialdir="C:/gui/", filetypes=(("Text Files", "*txt"), ("HTML Files", "*html")))
if text_file:
name = text_file
name = name.replace("C:/gui/", "")
root.title(f'{name} - NewNotepad')
text_file = open(text_file, 'w')
text_file.write(my_text.get(1.0, END))
text_file.close()
my_frame = Frame(root)
my_frame.pack(pady=5)
text_scroll = Scrollbar(my_frame)
text_scroll.pack(side=RIGHT, fill=Y)
my_text = Text(my_frame, width=97, height=25, font=("Helvetica", 16), selectbackground="Light Blue", selectforeground="Black", undo=True, yscrollcommand=text_scroll.set)
my_text.pack()
text_scroll.config(command=my_text.yview)
my_menu = Menu(root)
root.config(menu=my_menu)
file_menu = Menu(my_menu, tearoff=False)
my_menu.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="New", command=new_file)
file_menu.add_command(label="Open", command=open_file)
file_menu.add_command(label="Save")
file_menu.add_command(label="Save As", command=save_as_file)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=root.quit)
edit_menu = Menu(my_menu, tearoff=False)
my_menu.add_cascade(label="Edit", menu=edit_menu)
edit_menu.add_command(label="Cut")
edit_menu.add_command(label="Copy")
edit_menu.add_separator()
edit_menu.add_command(label="Undo")
edit_menu.add_command(label="Redo")
status_bar = Label(text="Ready", anchor=E)
status_bar.pack(fill=X, side=BOTTOM, ipady=5)
root.mainloop()
It may be because you used defaultextension=".*" in asksaveasfilename(). When you enter a filename without extension, .* will be appended to the filename and so the filename is an invalid filename.
Change defaultextension=".*" to defaultextension=".txt", for example, if you want to save the file with extension .txt if you do not enter file extension in the file dialog.
How do I force the button to change its text to the filename? Everything works fine, a dialog box opens and files open too. But I still can't change the button name to the file name and save it.
Here is the code:
import tkinter.filedialog as tfd
import tkinter as tk
import os
window = tk.Tk()
window.title("Op")
window.geometry("600x400")
window.resizable(False, False)
file_name = ""
def open():
global file_name
file_name = tfd.askopenfilename()
os.startfile(file_name) #open file
btn1 = tk.Button(window, text=f"Open {file_name}", command=open) #button
btn1.place(x = 20, y = 25)
You can set the buttons text property using.
button['text'] = fileName
You can also read the button text propeerty to make sure it has been set to the file name in code, I.e. with an if statement.
bText = button['text']
Try using .config -
import tkinter.filedialog as tfd
import tkinter as tk
import os
window = tk.Tk()
window.title("Op")
window.geometry("600x400")
window.resizable(False, False)
file_name = ""
def open():
global file_name
file_name = tfd.askopenfilename()
btn1.config(text=file_name) # Configure the button's text
os.startfile(file_name) #open file
btn1 = tk.Button(window, text=f"Open {file_name}", command=open) #button
btn1.place(x = 20, y = 25)
But if you run this code, the button name gets changed to the complete pathname (e.g. - C:/.../Choosen.file), so if you want only the file name ('Choosen.file') then use this -
btn1.config(text=file_name.split('/')[-1])
You can use:
window = tk.Tk()
window.title("Op")
window.geometry("600x400")
window.resizable(False, False)
file_name = ""
def open():
global file_name
file_name = tfd.askopenfilename()
btn1["text"] += " '" + file_name + "'"
os.startfile(file_name)
btn1 = tk.Button(window, text="Open file", command=open) # button
btn1.place(x=20, y=25)
tk.mainloop()
This uses the old text of the button and appends '{file_path}' to it -> Open file '{file_path}'
You could define a new class that maintains state. This way you can avoid the global, and will be able to make multiple buttons each with their own files.
class FileButton(tk.Button):
def __init__(self, window, file_name=""):
super().__init__(window, command=self.open)
self.set_text(file_name)
def set_text(self, file_name):
self.file_name = file_name
self["text"] = f"Open {self.file_name}"
def open(self):
if self.file_name == "":
self.set_text(tfd.askopenfilename())
os.startfile(self.file_name)
window = tk.Tk()
window.title("Op")
window.geometry("600x400")
window.resizable(False, False)
btn1 = FileButton(window)
btn1.place(x=20, y=25)
window.mainloop()
I'm trying to create a button to browse file and copy that file to a Master file and my code as below:
from tkinter import *
from tkinter import filedialog
def get_file_path():
global file_path
file_path= filedialog.askopenfilename(title = "Select A File", filetypes = (("xlsx", "*.xlsx"), ("xls", "*.xls"), ("xlsm", "*.xlsm"), ("All Files", "*.*")))
l1 = Label(window, text = file_path).pack()
window = Tk()
b1 = Button(window, text = "Open File", command = get_file_path).pack()
window.mainloop()
def close_window():
window.destroy()
print(file_path)
import openpyxl as xl
path1 = ("r'" and file_path)
path2 = (r'C:\Users\...\Write_Data.xlsx')
wb1 = xl.load_workbook(filename=path1)
ws1 = wb1["BASEL_LN_CTR"]
wb2 = xl.load_workbook(filename=path2)
ws2 = wb2["Loan Data"]
for row in ws1:
for cell in row:
ws2[cell.coordinate].value = cell.value
wb2.save(path2)
Everything is working well for me but I have to close window manually to print file_path. I would like to know that there is any way to close window aucomatically. I used destroy() but it not worked.
You created close_window() but you never use it.
You could create another button to run it (or to run directly window.destroy)
window = tk.Tk()
b1 = tk.Button(window, text="Open File", command=get_file_path).pack()
b2 = tk.Button(window, text="Close", comman=window.destroy).pack()
window.mainloop()
Or you should run it directly in get_file_path()
def get_file_path():
global file_path
file_path = filedialog.askopenfilename(title="Select A File", filetypes = (("xlsx", "*.xlsx"), ("xls", "*.xls"), ("xlsm", "*.xlsm"), ("All Files", "*.*")))
if file_path: # empty when pressed `Cancel`
#tk.Label(window, text=file_path).pack()
window.destroy()
This is probably a newbie question but I'm having issues figuring out how to get a value from a function, to be used as input in another.
I would also like to have some tips about code organization.
In this example I'm trying to get the filePath and outPut Folder path to be used in the function processFile.
Thank you
Code:
from tkinter import *
from tkinter import ttk
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import askdirectory
import PyPDF2
from PyPDF2 import PdfFileWriter, PdfFileReader
version = "v0.0.01"
root = Tk()
def window (main):
main.title("File Opener " + version)
width = main.winfo_width()
main.geometry('500x200')
numero = str(1)
def OpenFile():
fileName = askopenfilename(initialdir="C:/",
filetypes =(("PDF File", "*.pdf"),("All Files","*.*")),
title = "Select PDF File",
)
labelName = Label(text="File Path: " + fileName)
labelName.pack()
print(fileName)
return fileName
def outputFolder(): #Bug, label keeps adding paths
outPath = askdirectory()
labelName2 = Label(text="Output Folder: " + outPath)
labelName2.pack()
print(outPath)
return outPath
def processFile(inFile,outFolder):
''' print(fileName) get input name and output variables
print(outPath)'''
label = ttk.Label(root, text ="",foreground="black",font=("Helvetica", 16))
label.pack()
#Button Open-----------
button1 = Button (text = "Open File", command = OpenFile)
button1.pack()
#Button Start---------
buttonStart = Button (text = "Start Process", command = processFile)#give as parameter inputFile and link
buttonStart.place(height=50, width=100)
#Button Open-----------
button3 = Button (text = "Output Folder", command = outputFolder)
button3.pack()
#Menu Bar ----------------
menu = Menu(root)
root.config(menu=menu)
file = Menu(menu)
file.add_command(label = 'Open', command = OpenFile)
file.add_command(label = 'Exit', command = lambda:exit())
menu.add_cascade(label = 'File', menu = file)
window(root)
root.mainloop()
If you use the function in a variable the returned result from the function is stored in the variable.
def Function1(x):
return x*2
var1 = Function1(5)
Then var1 = 10.
But about your buttons, do you want to take input from the user that will be saved when the button is pressed or do you want the button to send a set value?
from tkinter import *
from tkinter import ttk
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import askdirectory
import PyPDF2
from PyPDF2 import PdfFileWriter, PdfFileReader
version = "v0.0.01"
root = Tk()
def window (main):
main.title("File Opener " + version)
width = main.winfo_width()
main.geometry('500x200')
main.configure(background = 'black')
numero = str(1)
#openFile
def OpenFile():
global fileName
fileName = askopenfilename(initialdir="C:/",
filetypes =(("PDF File", "*.pdf"),("All Files","*.*")),
title = "Select PDF File",
)
labelName = Label(text="File Path: " + fileName)
labelName.pack()
print(fileName)
return str(fileName)
#getOutputPath
def outputFolder(): #Bug, label keeps adding paths
outPath = askdirectory()
labelName2 = Label(text="Output Folder: " + outPath)
labelName2.pack()
print(outPath)
return outPath
#testFunct
def printFilename(inArg):
print(inArg)
x = OpenFile()
print (OpenFile())
lambda: printFilename(fileName)
#processRealDeal
def processFile(): #THIS IS THE MAIN FUNC
''' print(fileName) get input name and output variables
print(outPath)'''
print (OpenFile)
label = ttk.Label(root, text ="",foreground="black",font=("Helvetica", 16))
label.pack()
#Button Open-----------
button1 = Button (text = "Open File", command = OpenFile)
button1.pack()
#Button Start---------
buttonStart = Button (text = "Start Process", command = lambda: printFilename("Hello World!!!"))#give as parameter inputFile and link
buttonStart.place(height=50, width=100)
#Button Open-----------
button3 = Button (text = "Output Folder", command = outputFolder)
button3.pack()
#Menu Bar ----------------
menu = Menu(root)
root.config(menu=menu)
file = Menu(menu)
file.add_command(label = 'Open', command = OpenFile)
file.add_command(label = 'Exit', command = lambda:exit())
menu.add_cascade(label = 'File', menu = file)
window(root)
root.mainloop()
I cant see that you have declared the global fileName variabel outside the function.
I did this
from tkinter import *
from tkinter import ttk
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import askdirectory
import PyPDF2
from PyPDF2 import PdfFileWriter, PdfFileReader
version = "v0.0.01"
root = Tk()
fileName = "test"
def window (main):
main.title("File Opener " + version)
width = main.winfo_width()
main.geometry('500x200')
main.configure(background = 'black')
numero = str(1)
#openFile
def OpenFile():
global fileName
fileName = askopenfilename(initialdir="C:/",
filetypes =(("PDF File", "*.pdf"),("All Files","*.*")),
title = "Select PDF File",
)
labelName = Label(text="File Path: " + fileName)
labelName.pack()
test()
return str(fileName)
#getOutputPath
def test():
print(fileName)
def outputFolder(): #Bug, label keeps adding paths
outPath = askdirectory()
labelName2 = Label(text="Output Folder: " + outPath)
labelName2.pack()
print(outPath)
return outPath
#testFunct
def printFilename(inArg):
print(inArg)
x = OpenFile()
print (OpenFile())
lambda: printFilename(fileName)
#processRealDeal
def processFile(): #THIS IS THE MAIN FUNC
''' print(fileName) get input name and output variables
print(outPath)'''
print (OpenFile)
label = ttk.Label(root, text ="",foreground="black",font=("Helvetica", 16))
label.pack()
#Button Open-----------
button1 = Button (text = "Open File", command = OpenFile)
button1.pack()
#Button Start---------
buttonStart = Button (text = "Start Process", command = lambda: printFilename("Hello World!!!"))#give as parameter inputFile and link
buttonStart.place(height=50, width=100)
#Button Open-----------
button3 = Button (text = "Output Folder", command = outputFolder)
button3.pack()
#Menu Bar ----------------
menu = Menu(root)
root.config(menu=menu)
file = Menu(menu)
file.add_command(label = 'Open', command = OpenFile)
file.add_command(label = 'Exit', command = lambda:exit())
menu.add_cascade(label = 'File', menu = file)
window(root)
root.mainloop()
And the test function prints the chosen file. So the global variable is now containing the correct value.
So just declare it at the top and you will be able to retrieve the value
I am making a development environment type program with python and have a basic working program but I have a problem. I want to highlight certain words like import in a different color, like most development environments do but it wont work!
from tkinter import filedialog
from gameplay import *
from tkinter import *
import msvcrt as m
import os
openfileloc = ""
def combine_funcs(*funcs):
def combined_func(*args, **kwargs):
for f in funcs:
f(*args, **kwargs)
return combined_func
def load_file():
rootFd = Tk()
rootFd.withdraw()
file_path = filedialog.askopenfilename()
data = open(file_path, "r").read()
txtFd.delete('1.0', END)
txtFd.insert('1.0', data)
openfile = data
openfileloc = file_path
def save_file_dialog():
rootFd = Tk()
rootFd.withdraw()
wr = filedialog.asksaveasfile(mode='w', defaultextension=".br")
if wr.name != '':
wr.write(txtFd.get('1.0', "end"))
openfileloc = wr.name
wr.close()
def save_file():
if os.path.isfile(openfileloc):
os.remove(file_path)
wr = open(openfileloc, "w").write(txtFd.get('1.0', "end"))
else:
save_file_dialog()
def new_file():
txtFd.delete('1.0', END)
openfile = ""
openfileloc = ""
# HEY STACKOVERFLOW PROBLEM IS HERE
def highlightKeywords():
text = txtFd,get('1.0', 'end')
KeywordSet1 = ['import', 'if'] # Hilighted in Yellow
for i in range(len(text)):
if KeywordSet[i] in text:
txtFd.highlight_pattern(KeywordSet1[i], "yellow")
root = Tk()
root.title("GameBox Engine Editior - 0.0a")
menubar = Menu(root)
#Menu
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="New", command=new_file)
filemenu.add_command(label="Open", command=load_file)
filemenu.add_command(label="Save", command=save_file)
filemenu.add_command(label="Save as...", command=save_file_dialog)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)
root.config(menu=menubar)
txtFd = Text(root)
txtFd.pack()
root.mainloop()
# THIS IS WHERE I CALL THE FUNCTION
running = True
while(running):
m.getch()
highlightKeywords()
There are no errors, it just does not work. Can you help me?
Use (from http://effbot.org/tkinterbook/text.htm)
text.tag_configure('color', foreground='blue')
text.insert(END, "This is blue\n", 'color')
## you can also use relative position
text.tag_add('color', "1.0", "1.4")