I'm creating a GUI for my python script in EasyGUI. Does anyone know of a way I can change the default Window size? The default is far too big.
Thanks for your help.
Before install open easygui.py and edit element you want to have another size. (You can also reinstall and override it)
This will be line like
boxRoot.minsize(root_width, root_height)
in the corresponfing function.
To be more flexible add width and height as parameters to the function.
def __choicebox(msg
, title
, choices
, width_ = 480
, height_ = 320
):
....
root_width = width_
root_height = height_
root_xpos = int((screen_width * 0.1))
root_ypos = int((screen_height * 0.05))
boxRoot.title(title)
boxRoot.iconname('Dialog')
rootWindowPosition = "+0+0"
boxRoot.geometry(rootWindowPosition)
boxRoot.expand=NO
boxRoot.minsize(root_width, root_height)
I pseudo-pulled the code from GitHub to mess with the choicebox because of the size problem and I did the following .... I don't know if this is a good fix or not but it seemed to work to make at least the width of the screen variable according to the length of msg, title, and list of choices:
...
choices = list(choices[:])
add lines
choiceLen = len(max(choices,key=len))
titleLen = len(title)
msgLen = len(msg)
maxLen = max(choiceLen,titleLen,msgLen)
...
root_width = int((screen_width * 0.8))
root_width = int(maxLen * 10.)
Related
More specifically... I used (and a bit modified, but nothing much) the code from latextools webpage.
import latextools
import drawSvg as draw
def renderLatexEquation(f):
latex_eq = latextools.render_snippet(r'$' + f + r'$', commands=[latextools.cmd.all_math])
return latex_eq.as_svg()
d = draw.Drawing(100, 100, origin='center', displayInline=False)
d.append(draw.Circle(0, 0, 49, fill='yellow', stroke='black', stroke_width=2))
d.draw(renderLatexEquation(r'x^2'), x=0, y=0, center=True, scale=2.5)
d.saveSvg('vector.svg')
The result looks almost perfect, the only problem - the "x" has a tiny bit of it cut off (at the bottom). How can I fix that? Thank you for any hints!
Okay, maybe this isn't the best solution, but it still works.
I compiled whole pdf (using 'standalone' documentclass with border equal to 1pt) and then converted it to svg.
import latextools
import drawSvg as draw
def renderLatexEquation(f, border = '1pt'):
packages = []
commands = []
config = latextools.DocumentConfig('standalone', ('border=' + border,))
proj = latextools.LatexProject()
content = latextools.BasicContent(r'$'+f+r'$')
doc = content.as_document(path='figs/test.tex', config=config)
doc = latextools.LatexDocument(path='figs/test.tex', config=config, contents=(content,))
proj.add_file(doc)
proj.write_src('.')
proj.add_file(latextools.LatexDocument(path='main.tex', config=config, contents=doc.contents))
pdf = proj.compile_pdf()
# pdf.save('figs/test.pdf')
return pdf.as_svg()
d = draw.Drawing(100, 100, origin='center', displayInline=False)
d.draw(renderLatexEquation('x^3'), x=0, y=0, center=True, scale=2.5, stroke='black')
d.saveSvg('test.svg')
I'm trying to have a progress window which shows the progress, alongside having tasks happening in the background. Everything works as expected, except the window partially loads on to the screen (how much of it does depends on every run). Here is the relevant part of the code:
def loading(): #Displays loading progress while setting up the exam
global load, progress
load = Toplevel()
load.title("Loading")
load.attributes('-topmost', True)
load.overrideredirect(True)
lab = Label(load, text = ("Preparing Your Exam, Please Wait!\nPlease DO NOT Open any Other Window.\n"
+"Doing so may lead to immidiate Termination."))
lab.grid(row = 0, column = 1, padx = 20, pady = 20)
progress=Progressbar(load,orient=HORIZONTAL,length=200,mode='determinate')
progress.grid(row = 1, column = 1, padx = 20, pady = 20)
log = Label(load, image = logo)
log.image = logo
log.grid(row = 0, column = 0, rowspan = 2, padx = 20, pady = 20)
w_req, h_req = load.winfo_width(), load.winfo_height()
w_form = load.winfo_rootx() - load.winfo_x()
w = w_req + w_form*2
h = h_req + (load.winfo_rooty() - load.winfo_y()) + w_form
x = (load.winfo_screenwidth() // 2) - (w // 2)
y = (load.winfo_screenheight() // 2) - (h // 2)
load.geometry(f'{w_req}x{h_req}+{x}+{y}')
Here's what happens after calling loading:
loading()
conv_th = Thread(target = Convert).start()
The Convert function converts and processes images, I'm not sharing that because it might not be relevant.
I far as I think, it might be because it is not getting enough time to load completely, but I couldn't really figure out what could be causing the program to behave this way. Any help will be appreciated!
Update: This behavior is seen even if conv_th = Thread(target = Convert).start() is omitted, implying that there could be a problem within the loading() function.
So, I ended up solving the problem myself. I'm telling the reason that I think is most probable, please correct me if the reason that I give is incorrect or there is another solution for this.
This part of the code,
w_req, h_req = load.winfo_width(), load.winfo_height()
w_form = load.winfo_rootx() - load.winfo_x()
w = w_req + w_form*2
h = h_req + (load.winfo_rooty() - load.winfo_y()) + w_form
x = (load.winfo_screenwidth() // 2) - (w // 2)
y = (load.winfo_screenheight() // 2) - (h // 2)
was being executed too early, before the window could actually load itself up completely, and hence whatever amount of it got loaded before this, was taken as the dimensions and then the values were set.
Adding the command load.update_idletasks() before the above part of the code resolved the problem. Thanks #martineau, your comment was really helpful in figuring this out.
I'm trying to transform a method into a int (i need to divide the method value for 2)
width = int(post.width) / 2
height = int(post.height) / 2
but it gives me this error:
TypeError: int() argument must be a string, a bytes-like object or a number, not 'method'
Is there any method to do it?
Edit:
For those who're trying to help me, i want to import an image (with Pil, tkinter) but with the half of his size.
post1 = Image.open(directory)
width = int(post.width) / 2
height = int(post.height) / 2
canvas=Canvas(root,width=width,height=height)
canvas.create_image(0,0,anchor=NW,image=post)
canvas.pack(padx=20, pady=20)
Also, if you need it, i provide you the complete script:
from minio import Minio
import tkinter as tk
from tkinter import *
from PIL import Image, ImageTk
import random
import os
root = Tk()
root.title("Ripetra")
width_value = root.winfo_screenwidth()
height_value = root.winfo_screenheight()
minio = Minio('myip',
access_key='key',
secret_key='key',
)
immagini = minio.list_objects('ripetra', recursive=True)
names = [img2.object_name for img2 in immagini]
image = random.choice(names)
imagecanvas = minio.fget_object("ripetra", image, "cont/ft/" + image)
dir = os.path.join("cont/ft/", image)
post1 = Image.open(dir)
resized = post1.resize((width_value, height_value), Image.ANTIALIAS)
post = ImageTk.PhotoImage(resized)
width = int(post.width()) / 2
height = int(post.height()) / 2
canvas=Canvas(root,width=width,height=height)
canvas.create_image(0,0,anchor=NW,image=post)
canvas.pack(padx=20, pady=20)
root.mainloop()
You should put () after each method name, since what you want to do is call the method. What your code is currently trying to do is convert a piece of python code to an integer which is non-sensical.
Try doing this :
width = int(post.width()) / 2
height = int(post.height()) / 2
All though I think actually you probably need this :
width = int(post.width() / 2)
height = int(post.height() / 2)
That is you want to convert the value to an integer after the division in case one of the values returned is odd.
You probably forgot parenthesis after .width and .height :
width = int(post.width()) / 2
height = int(post.height()) / 2
Let me start by posting some little helper functions I'll use to formulate my questions:
import textwrap
import sys
from pathlib import Path
from PyQt5.Qsci import QsciScintilla
from PyQt5.Qt import * # noqa
def set_style(sci):
# Set default font
sci.font = QFont()
sci.font.setFamily('Consolas')
sci.font.setFixedPitch(True)
sci.font.setPointSize(8)
sci.font.setBold(True)
sci.setFont(sci.font)
sci.setMarginsFont(sci.font)
sci.setUtf8(True)
# Set paper
sci.setPaper(QColor(39, 40, 34))
# Set margin defaults
fontmetrics = QFontMetrics(sci.font)
sci.setMarginsFont(sci.font)
sci.setMarginWidth(0, fontmetrics.width("000") + 6)
sci.setMarginLineNumbers(0, True)
sci.setMarginsForegroundColor(QColor(128, 128, 128))
sci.setMarginsBackgroundColor(QColor(39, 40, 34))
sci.setMarginType(1, sci.SymbolMargin)
sci.setMarginWidth(1, 12)
# Set indentation defaults
sci.setIndentationsUseTabs(False)
sci.setIndentationWidth(4)
sci.setBackspaceUnindents(True)
sci.setIndentationGuides(True)
sci.setFoldMarginColors(QColor(39, 40, 34), QColor(39, 40, 34))
# Set caret defaults
sci.setCaretForegroundColor(QColor(247, 247, 241))
sci.setCaretWidth(2)
# Set edge defaults
sci.setEdgeColumn(80)
sci.setEdgeColor(QColor(221, 221, 221))
sci.setEdgeMode(sci.EdgeLine)
# Set folding defaults (http://www.scintilla.org/ScintillaDoc.html#Folding)
sci.setFolding(QsciScintilla.CircledFoldStyle)
# Set wrapping
sci.setWrapMode(sci.WrapNone)
# Set selection color defaults
sci.setSelectionBackgroundColor(QColor(61, 61, 52))
sci.resetSelectionForegroundColor()
# Set scrollwidth defaults
sci.SendScintilla(QsciScintilla.SCI_SETSCROLLWIDTHTRACKING, 1)
# Current line visible with special background color
sci.setCaretLineBackgroundColor(QColor(255, 255, 224))
# Set multiselection defaults
sci.SendScintilla(QsciScintilla.SCI_SETMULTIPLESELECTION, True)
sci.SendScintilla(QsciScintilla.SCI_SETMULTIPASTE, 1)
sci.SendScintilla(QsciScintilla.SCI_SETADDITIONALSELECTIONTYPING, True)
def set_state1(sci):
sci.clear_selections()
base = "line{} state1"
view.setText("\n".join([base.format(i) for i in range(10)]))
for i in range(0, 10, 2):
region = (len(base) * i, len(base) * (i + 1) - 1)
if i == 0:
view.set_selection(region)
else:
view.add_selection(region)
def set_state2(sci):
base = "line{} state2"
view.setText("\n".join([base.format(i) for i in range(10)]))
for i in range(1, 10, 2):
region = (len(base) * i, len(base) * (i + 1) - 1)
if i == 1:
view.set_selection(region)
else:
view.add_selection(region)
class Editor(QsciScintilla):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
set_style(self)
def clear_selections(self):
sci = self
sci.SendScintilla(sci.SCI_CLEARSELECTIONS)
def set_selection(self, r):
sci = self
sci.SendScintilla(sci.SCI_SETSELECTION, r[1], r[0])
def add_selection(self, r):
sci = self
sci.SendScintilla(sci.SCI_ADDSELECTION, r[1], r[0])
def sel(self):
sci = self
regions = []
for i in range(sci.SendScintilla(sci.SCI_GETSELECTIONS)):
regions.append(
sci.SendScintilla(sci.SCI_GETSELECTIONNSTART, i),
sci.SendScintilla(sci.SCI_GETSELECTIONNEND, i)
)
return sorted(regions)
I've got a couple of questions actually:
Question 1)
if __name__ == '__main__':
app = QApplication(sys.argv)
view = Editor()
set_state1(view)
view.move(1000, 100)
view.resize(800, 300)
view.show()
app.exec_()
I'll get this (you can see the question in the below snapshot):
Question 2)
if __name__ == '__main__':
app = QApplication(sys.argv)
view = Editor()
set_state1(view)
set_state2(view)
view.move(1000, 100)
view.resize(800, 300)
view.show()
app.exec_()
How can I modify the code so I'll be able to restore state1 when pressing ctrl+z?
Right now when using ctrl+z you won't be able to get state1:
mainly because how setText behaves:
Replaces all of the current text with text. Note that the undo/redo
history is cleared by this function.
I've already tried some of the functions posted in the undo and redo docs but no luck so far.
For instance, one of my attempts has been first selecting all text and then using replaceSelectedText and finally restoring the selections from the previous state manually, the result was ugly (i don't want the editor scrolling messing up when undoing/redoing)... Basically, I'd like to get the same feeling than SublimeText.
Btw, this is a little minimal example but in the real-case I'll be accumulating a bunch of operations without committing to scintilla very often... that's why I'm interested to figure out how to rollback to a previous state when using the undoable setText... Said otherwise, i'd like to avoid using Scintilla functions such as insertAt, replaceSelectedText or similars... as I'm using python string builtin functions to modify the buffer internally.
EDIT:
I'm pretty sure beginUndoAction & endUndoAction won't help me to answer question2 but... what about SCI_ADDUNDOACTION? Although the docs are pretty confusing though... :/
Question 1:
The last selection added is automatically set as the Main selection. To remove it, add line sci.SendScintilla(sci.SCI_SETMAINSELECTION, -1) at the end of the set_state1 function.
Question 2:
The way you described it by storing the selections, using the replaceSelectedText, and then using setCursorPosition / reselecting all selections and setFirstVisibleLine to restore the scroll position is one way to go.
Looking at the C++ source of the setText function:
// Set the given text.
void QsciScintilla::setText(const QString &text)
{
bool ro = ensureRW();
SendScintilla(SCI_SETTEXT, ScintillaBytesConstData(textAsBytes(text)));
SendScintilla(SCI_EMPTYUNDOBUFFER);
setReadOnly(ro);
}
You could try setting the text using sci.SendScintilla(sci.SCI_SETTEXT, b"some text"), which doesn't reset the undo/redo buffer.
I need to write a script that does the following:
# open a tiff
# get it's dpi, width, height and colorspace
# set the dpi, width, height and colorspace
# and then save the tiff out with no compression and no layers.
So far I've gotten:
from win32com.client.dynamic import Dispatch
ps = Dispatch( "Photoshop.Application" )
file_path = "C:\\Users\\me\\myImg.tif"
doc = ps.Open( file_path )
dpi = doc.Resolution
width = doc.Width # in cm
height = doc.Height # in cm
# up to here the code works, but then I try
doc.Resolution = 72
ps.ResizeImage( 120 , 120 )
ps.PsColorSpaceType( 3 ) # psSRGB
ps.TiffSaveOptions.ImageCompression = 1 # psNoTIFFCompression
ps.TiffSaveOptions.Layers = False
ps.Save()
# and this last section fails
Please help, any ideas, tips, soultions would be greatly appreciated :D
After a lot of googeling and some trial and error and then even more trial and error I've managed to come up with the code below.
Hope this can help someone else.
Code
file_path = "C:\\Users\\me\\myImg.tif"
color_settings = "North America General Purpose 2"
from win32com.client.dynamic import Dispatch
ps_app = Dispatch( "Photoshop.Application" )
# set photoshop to use pixels as dimensions
ps_app.Preferences.RulerUnits = 1 # 'for PsUnits --> 1 (psPixels)
ps_app.Preferences.TypeUnits = 1 # 'for PsTypeUnits --> 1 (psPixels)
doc = ps_app.Open( file_path ) # Open a file and store open file as doc
dpi = doc.Resolution
width = doc.Width
height = doc.Height
cor_res = 1024
ps_app.ChangeColorSettings( color_settings )
doc.ResizeImage( cor_res , cor_res , 72 )
options = Dispatch('Photoshop.TiffSaveOptions')
options.ImageCompression = 1 # ps_appNoTIFFCompression
options.Layers = False # no layers
doc.SaveAs( file_path , options ) # Save with specified options
doc.Close( 2 ) # psDoNotSaveChanges