Tkinter theme is not working, just displays as regular - python

I'm trying to use the theme "sun valley" for a python-based installer that i'm working on. I have all the .tcl files installed and everything should be working, but its not. I even tried to use the built in styles
here's my code:
from tkinter import *
from tkinter import ttk
from tkinter.ttk import *
import os
director = os.path.dirname(__file__)
friendlyName = "python"
file = ""
import shutil
global User
try:
User = os.getlogin()
except:
User="home"
from tkinter import *
from tkinter import filedialog
from os import path
path = fr"C:\{User}\AppData\Local\{friendlyName}"
def install():
try:
os.mkdir(path)
except:
pass
shutil.copy(file, path)
#E1 = Entry(top, bd =5)
window = Tk()
# Just simply import the azure.tcl file
style = ttk.Style(window)
dir_path = os.path.dirname(os.path.realpath(__file__))
window.tk.call('source', os.path.join(dir_path, 'theme\dark.tcl'))
print(os.path.join(dir_path, 'theme\dark.tcl'))
#window.tk.call("set_theme", "dark")
style.theme_use('sun-valley-dark')
window.geometry("600x400")
window.rowconfigure(20)
window.columnconfigure(20)
def askdir():
direct = filedialog.askdirectory()
path = direct
textBox.delete(0, END)
textBox.insert(0, path)
#textBox.set(path)
window.update_idletasks()
window.title(f"{friendlyName} install")
chooseText = Label(window, text=f"choose a place for {friendlyName} to be installed")
chooseText.grid(column=2, row=0)
chooseButton = Button(window, text="choose path", command=askdir)
chooseButton.grid(column=1, row=3)
textBox = Entry(window, text=f"{path}")
textBox.insert(0, path)
textBox.grid(column=2, row=3)
chooseButton = Button(window, text="install", command=install)
chooseButton.grid(column=3, row=4)
chooseButton = Button(window, text="quit", command=window.destroy)
chooseButton.grid(column=1, row=4)
window.mainloop()
heres what outputs:

Need to use ttk widgets
instead of chooseText = Label(window, text=f"choose a place for {friendlyName} to be installed")
it would be chooseText = ttk.Label(window, text=f"choose a place for {friendlyName} to be installed")
then the style will show up!

Related

changing extensions of all images in a folder with tkinter

I want to convert the image formats of all images in a folder using tkinter. all extensions I want in a combobox but I don't know why this code doesn't work .no error is displayed.
from tkinter import filedialog, StringVar
from tkinter import ttk
root=tkinter.Tk()
root.geometry("800x600")
#defining functions
def get_folder():
global folder_path
folder_path = filedialog.askdirectory(initialdir='./', title="Select Folder")
print(folder_path)
def get_extension():
change_to = com.get()
change_from = "py"
files=os.listdir(folder_path)
for file in files:
if (".%s"%change_from) in file:
newfile=file.replace((".%s"%change_from),".%s"%change_to)
os.rename((folder_path+'/'+file),(folder_path+'/'+newfile))
#defining widgets for frames
folder_label = tkinter.Label(from_frame)
browse_button = tkinter.Button(from_frame, text="Browse", command=get_folder)
change_button = tkinter.Button(button_frame, text="Change Extension", command=get_extension)
change_button.pack()
#defining combobox
com = StringVar()
list_combo = ['.png','.jpg','.jpeg', '.svg', '.tif','.bmp','.gif','ppm']
combox = ttk.Combobox(root, width = 25, font = 'arial 19 bold', value = list_combo, state = 'r', textvariable = com)
combox.place(x= 190, y= 190)
combox.set('select type')
root.configure(bg = 'coral1')
root.mainloop()```
Is this what You want:
from tkinter import Tk, Button, Label, StringVar, Frame
from tkinter.ttk import Combobox
from tkinter.filedialog import askdirectory
import os
def convert_extensions():
path = dir_lbl.cget('text')
from_ = from_var.get()
to_ = to_var.get()
files_from = [f'{path}/{file}' for file in os.listdir(path) if file.split('.')[-1] == from_]
files_to = ['.'.join(file.split('.')[:-1]) + '.' + file.split('.')[-1].replace(from_, to_) for file in files_from]
for from_file, to_file in zip(files_from, files_to):
os.rename(from_file, to_file)
print(f'{"-" * 100}\n'
f'{"From:": <10} {from_file}\n'
f'{"To:": <10} {to_file}\n')
root = Tk()
root.geometry('500x200')
Button(root, text='Choose Directory', command=lambda: dir_lbl.config(text=askdirectory())).pack(pady=5)
dir_lbl = Label(root, text='')
dir_lbl.pack(pady=5)
options_frame = Frame(root)
options_frame.pack(pady=5)
from_var = StringVar(value='Convert from')
list_combo = ['png', 'jpg', 'jpeg', 'svg', 'tif', 'bmp', 'gif', 'ppm']
Combobox(options_frame, value=list_combo,
textvariable=from_var, state='r').pack(side='left', padx=5, pady=5)
to_var = StringVar(value='Convert to')
Combobox(options_frame, value=list_combo,
textvariable=to_var, state='r').pack(side='left', padx=5, pady=5)
Button(root, text='Convert', command=convert_extensions).pack(pady=5)
root.mainloop()
This however allows more control in that You can choose both the extension to convert and to which one convert.
This is pretty basic so if You have any questions, ask. I will probably add a detailed explanation later but for now this is all I can do. Oh and btw that three line print function is not necessary at all and it probably should be made to display that in tkinter window or sth but otherwise it can be removed.

Browse Functionality in Tkinter

I'm trying the implement the browse functionality in Tkinter, I'm able to implement the browse file option, however, after selecting the file at a particular location it's displaying file location on the console, how to print that location on the label?
At the following place, file_location or file_name should be printed.
entry_1.insert(0, 'File_location')
For e.g. the file location is
Path with file name C:\Users\Desktop\test\test.txt
, so this file location should be printed on the label instead of the console.
And along with that, if I want only a path without a file name then how it can be done?
Path without file name. C:\Users\Desktop\test
What extra functionality do I need to add in order to implement this feature? Any help would be appreciated.
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from io import StringIO
import sys
import os
root = Tk()
root.geometry('700x650')
root.title("Data Form")
def file_opener():
input = filedialog.askopenfiles(initialdir="/")
print(input)
for i in input:
print(i)
label_1 = Label(root, text="Location",width=20,font=("bold", 10))
label_1.place(x=65,y=130)
x= Button(root, text='Browse',command=file_opener,width=6,bg='gray',fg='white')
x.place(x=575,y=130)
entry_1 = Entry(root)
entry_1.place(x=240,y=130,height=20, width=300)
entry_1.insert(0, 'File_location')
root.mainloop()
Instead of using
filedialog.askopenfile(initialdir="/")
use
filedialog.askopenfilename(initialdir="/")
if you want to select multiple files and get a tuple as the input use
filedialog.askopenfilenames(initialdir="/")
And for the path without the file name use this
import os
os.path.dirname(input)
you can Insert the text to the Entry by using this
Updated:
entry_1.delete(0, END)
entry_1.insert(0, input[0])
Full Modified code
(Updated:)
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from io import StringIO
import sys
import os
root = Tk()
root.geometry('700x650')
root.title("Data Form")
def file_opener():
# input = filedialog.askopenfilenames(initialdir="/") # for selecting multiple files
input = filedialog.askopenfilename(initialdir="/")
entry_1.delete(0, END)
entry_1.insert(0, input)
label_1 = Label(root, text="Location", width=20, font=("bold", 10))
label_1.place(x=65, y=130)
x = Button(root, text='Browse', command=file_opener, width=6, bg='gray', fg='white')
x.place(x=575, y=130)
entry_1 = Entry(root)
entry_1.place(x=240, y=130, height=20, width=300)
entry_1.insert(0, 'File_location')
root.mainloop()

Put file path in global variable from browse button with tkinter

I'm just starting to use tkinter and it is a little difficult to handle it. Check this sample :
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import Tkinter as tk
import tkFileDialog
def openfile():
filename = tkFileDialog.askopenfilename(title="Open file")
return filename
window = tk.Tk()
tk.Button(window, text='Browse', command=openfile).pack()
window.mainloop()
I juste created a browse button which keep the file path in the variable "filename" in the function openfile(). How can i put the content of "filename" in a variable out of the function ?
For example I want to put it in the variable P and print it in a terminal
def openfile():
filename = tkFileDialog.askopenfilename(title="Open file")
return filename
window = tk.Tk()
tk.Button(window, text='Browse', command=openfile).pack()
window.mainloop()
P = "the file path in filename"
print P
I also also want to put the file path in a widget Entry(), and as same as below, get the text in the Entry widget in another global variable.
If someone knows, it would be nice.
There are at least two different ways of doing it:
1) Bundle your whole app in a class like this:
import Tkinter as tk
import tkFileDialog
class App(tk.Tk):
def __init__(self):
tk.Tk.__init__(self) # create window
self.filename = "" # variable to store filename
tk.Button(self, text='Browse', command=self.openfile).pack()
tk.Button(self, text='Print filename', command=self.printfile).pack()
self.spinbox = tk.Spinbox(self, from_=0, to=10)
self.spinbox.pack(pady=10)
tk.Button(self, text='Print spinbox value', command=self.printspinbox).pack()
self.mainloop()
def printspinbox(self):
print(self.spinbox.get())
def openfile(self):
self.filename = tkFileDialog.askopenfilename(title="Open file")
def printfile(self):
print(self.filename)
if __name__ == '__main__':
App()
In this case, filename is an attribute of the App, so it is accessible from any function inside the class.
2) Use a global variable:
import Tkinter as tk
import tkFileDialog
def openfile():
global filename
filename = tkFileDialog.askopenfilename(title="Open file")
def printfile():
print(filename)
def printspinbox():
print(spinbox.get())
window = tk.Tk()
filename = "" # global variable
tk.Button(window, text='Browse', command=openfile).pack()
tk.Button(window, text='Print filename', command=printfile).pack()
spinbox = tk.Spinbox(window, from_=0, to=10)
spinbox.pack(pady=10)
tk.Button(window, text='Print spinbox value', command=printspinbox).pack()
window.mainloop()

NameError: name 'tkFileDialog' is not defined

I'm trying to use Tkinter and get the user to choose a certain file. My code looks like this (I'm just starting out with Tkinter)
from Tkinter import *
from tkFileDialog import *
root = Tk()
root.wm_title("Pages to PDF")
root.wm_iconbitmap('icon.ico')
w = Label(root, text="Please choose a .pages file to convert.")
y = tkFileDialog.askopenfilename(parent=root)
y.pack()
w.pack()
root.mainloop()
When I run the program, I get an error that says:
NameError: name 'tkFileDialog' is not defined
I've tried it with a few configurations I found online. None of them have worked; but this is the same basic error every time. How can I fix this?
You are importing everything from tkFileDialog module, so you don't need to write a module-name prefixed tkFileDialog.askopenfilename(), just askopenfilename(), like:
from Tkinter import *
from tkFileDialog import *
root = Tk()
root.wm_title("Pages to PDF")
w = Label(root, text="Please choose a .pages file to convert.")
fileName = askopenfilename(parent=root)
w.pack()
root.mainloop()
Try this:
from Tkinter import *
import tkFileDialog
root = Tk()
root.wm_title("Pages to PDF")
root.wm_iconbitmap('icon.ico')
w = Label(root, text="Please choose a .pages file to convert.")
y = tkFileDialog.askopenfilename(parent=root)
y.pack()
w.pack()
root.mainloop()
Seems a space name problem.
Try this:
try:
import Tkinter as tk
import tkFileDialog as fd
except:
import tkinter as tk
from tkinter import filedialog as fd
def NewFile():
print("New File!")
def OpenFile():
name = fd.askopenfilename()
print(name)
def About():
print("This is a simple example of a menu")
class myGUI:
def __init__(self, root):
self.root = root
self.canvas = tk.Canvas(self.root,
borderwidth=1,
relief="sunken")
self.canvas.pack( fill=tk.BOTH, expand=tk.YES)
self.menu = tk.Menu(self.root)
self.root.config(menu=self.menu)
self.helpmenu = tk.Menu(self.menu)
self.filemenu = tk.Menu( self.menu )
self.menu.add_cascade(label="File", menu=self.filemenu)
self.filemenu.add_command(label="New", command=NewFile)
self.filemenu.add_command(label="Open...", command=OpenFile)
self.filemenu.add_separator()
self.filemenu.add_command(label="Exit", command=root.destroy)
root = tk.Tk()
root.title('appName')
myGUI(root)
root.mainloop()

how to get the file path from Python GUI and use file path in another python program

This is my main file:
ExcelAppl = win32com.client.Dispatch('Excel.Application')
Workbook = ExcelAppl.Workbooks.Open('excel file path')
Sheet = Workbook.Worksheets.Item(1)
This is the Python GUI:
root = Tk()
def callback():
file_path = tkFileDialog.askopenfilename(filetypes=[("Excel files","*.xls")])
print "the file path %s",file_path
Text_button.insert(INSERT,file_path)
def execute():
execfile("MainLibrary.py")
Browse_button = Button(text='Browse', command=callback).pack(side=LEFT, padx=10, pady=20, ipadx=20, ipady=10)
Execution_button = Button(text='Convert', command=execute).pack(side=BOTTOM, padx=10, pady=20, ipadx=20, ipady=10)
root.mainloop()
This is my query. I need to get the file_path from the GUI and assign it to Workbook = ExcelAppl.Workbooks.Open('excel file path'). I need to get the path from the GUI and assign the path to my main code. Can anyone help?
You don't need execfile() here.
You could define a function in main_library.py instead:
import win32com.client
def do_something_with_excel_file(filename):
app = win32com.client.Dispatch('Excel.Application')
workbook = app.Workbooks.Open(filename)
worksheet = workbook.Worksheets.Item(1)
# use `worksheet` ...
if __name__=="__main__":
import sys
# get filename from command-line if called as a script
do_something_with_excel_file(sys.argv[1])
Then you could import it in your GUI code:
import tkFileDialog
from Tkinter import as tk
import main_library
def browse():
path = tkFileDialog.askopenfilename(filetypes=[("Excel files","*.xls")])
file_path.set(path)
print "the file path %s", path
def convert():
root.destroy() # quit gui
main_library.do_something_with_excel_file(file_path.get())
root = tk.Tk()
file_path = tk.StringVar()
tk.Label(root, textvariable=file_path).pack()
tk.Button(text='Browse', command=browse).pack()
tk.Button(text='Convert', command=convert).pack()
root.mainloop()

Categories

Resources