473,662 Members | 2,524 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

tkinter text width

Hello All,

I would like for a tkinter text widget to be aware of how big the frame that
contains it is, then I would like for it to reset its width to the
appropriate number of characters when this frame changes size.

I can get a cget("width") for the text, but this does not dynamically reflect
the visible width.

One way I can think of is getting the size of the font used in the widget then
getting the width of the frame with cget then doing the appropriate math and
configuring the text widget upon resize events.

I'm thinking that there must be a more straightforward way.

Any ideas?

James
--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
Jul 19 '05 #1
8 11296
On Tue, 26 Apr 2005 17:01:46 -0700, James Stroud <js*****@mbi.uc la.edu> wrote:
Hello All,

I would like for a tkinter text widget to be aware of how big the frame that
contains it is, then I would like for it to reset its width to the
appropriate number of characters when this frame changes size.


Errr... This is supposed to be the regular behaviour. How do you create your Text widget? Do you specify a width and height? If you do not, the default width and height are 80 and 24 respectively, and the widget won't resize to less than that. If you want a Text widget to be the smallest as possible in its container, you can do something like:

-----------------------------------------------------
from Tkinter import *

root = Tk()

t = Text(root, width=1, height=1)
t.pack(fill=BOT H, expand=1)

root.geometry(' 500x200')

root.mainloop()
-----------------------------------------------------

The "trick" is to create the Text as small as possible (width=1, height=1), make it fill its whole container (pack(fill=BOTH , expand=1)), then set the dimensions for the container window (geometry('500x 200')). You'll get a Text that will shrink and expand as much as you like.

Is it what you were after?

HTH
--
python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz 5(17;8(%,5.Z65\ \'*9--56l7+-'])"
Jul 19 '05 #2
On Wednesday 27 April 2005 02:31 am, so sayeth Eric Brunel:
The "trick" is to create the Text as small as possible (width=1, height=1),
make it fill its whole container (pack(fill=BOTH , expand=1)), then set the
dimensions for the container window (geometry('500x 200')). You'll get a
Text that will shrink and expand as much as you like.

Is it what you were after?


This is more or less what I would like, but I would also like to probe the
Text to see how many characters it thinks it can display within the container
window. I am formatting text dynamically and so I rely on the width. I am not
after the built in "wrap" option, it does not do what I want. But, say if
wrap were turned on, it would be good to know how many characters the Text
would wrap at.

James

--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
Jul 19 '05 #3
On Wed, 27 Apr 2005 10:52:14 -0700, James Stroud wrote:
This is more or less what I would like, but I would also like to probe the
Text to see how many characters it thinks it can display within the container
window. I am formatting text dynamically and so I rely on the width. I am not
after the built in "wrap" option, it does not do what I want. But, say if
wrap were turned on, it would be good to know how many characters the Text
would wrap at.


I have extensive experience with trying to get text containers to do this.
It is not easy. You have two choices:

1. Give up. You can't tell anyhow if you're using a proportional font.

2. Use a fixed-width font and manually wrap. (It's pretty easy then, you
can ask the font for how wide any char is and do the math from there.)

I have 70 line function that tries to replicate the Tk wrapping algorithm
in the proportional text case, and it *still* doesn't work. For one thing,
I actually found some bugs in the wrapping code (if a Unicode character
gets into just the right position, it can actually run off the right end
of the text widget, even if the widget is being wrapped), so completely
matching the layout seems infeasible.

I would strongly, strongly suggest finding another way to do what you are
trying to do. I have blown many, many hours on this problem, and I found
no simple logic. The edge cases kill you; while Tk is consistent (same
text, same wrap every time), sometimes it wraps a word if it goes up to
the edge, sometimes if it's one pixel off, damned if I can find a pattern
(probably has something to do with trying to space the letters out,
kerning or one of its simpler friends), and it probably changes
periodically anyhow... and note based on this I can't even guarantee #2
above, if you get unlucky.

Basically, I'm pretty sure you can't do this.

Jul 19 '05 #4
Thank you to everybody helping me. I think I am almost there...

On Wednesday 27 April 2005 12:10 pm, so sayeth Jeremy Bowers:
2. Use a fixed-width font and manually wrap. (It's pretty easy then, you
can ask the font for how wide any char is and do the math from there.)
How might I query the size of a fixed-width font in pixles? It appears that
the width of the font in points does not correlate with its width in pixels
based on some simple expriments I have done. Using cget("font") on the Text
gives back a string with the point size.
[snip some things to worry about]
Basically, I'm pretty sure you can't do this.


My setup is not very complicated, so I don't think I have to worry about
kerning, unicode, etc.. I am using a fixed width font (courier) only, and
only one size and am also quite comfortable with giving away several pixels
at the end of a line for "rounding errors" and will filter for a limited
alphabet consisting only of the numbers, the captial letters, and the space.

I think I can do this given these limitations.

James

--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
Jul 19 '05 #5
On Wed, 27 Apr 2005 12:52:21 -0700, James Stroud wrote:
Thank you to everybody helping me. I think I am almost there...

On Wednesday 27 April 2005 12:10 pm, so sayeth Jeremy Bowers:
2. Use a fixed-width font and manually wrap. (It's pretty easy then, you
can ask the font for how wide any char is and do the math from there.)
How might I query the size of a fixed-width font in pixles? It appears that
the width of the font in points does not correlate with its width in pixels
based on some simple expriments I have done. Using cget("font") on the Text
gives back a string with the point size.


Ah, in that case you want the measure attribute of the font object.

http://www.pythonware.com/library/tk...71-methods.htm
[snip some things to worry about]
Basically, I'm pretty sure you can't do this.


My setup is not very complicated, so I don't think I have to worry about
kerning, unicode, etc.. I am using a fixed width font (courier) only, and
only one size and am also quite comfortable with giving away several pixels
at the end of a line for "rounding errors" and will filter for a limited
alphabet consisting only of the numbers, the captial letters, and the space.

I think I can do this given these limitations.


Sounds like it.

What I did was set up unit test that threw random snippets at the text
widget, and compared how many lines my code thought the widget should
have, vs. what the widget claimed to have. This is how I discovered that
some unicode was wrapped incorrectly. You can get what the widget claims
to have by asking it for the geometric position of the last character with
the bbox method of the Text widget.

This is, however, probably not the answer you are looking for, because you
only get a bounding box if the text is currently visible on the screen.
This makes it fairly difficult to use to ask the widget *how far* off the
screen the text is. If it were that easy I would have said so earlier
:-) But you may find that useful too, as you cobble together a solution.

Jul 19 '05 #6
On Wed, 27 Apr 2005 12:52:21 -0700, James Stroud <js*****@mbi.uc la.edu> wrote:

[snip]
How might I query the size of a fixed-width font in pixles? It appears that
the width of the font in points does not correlate with its width in pixels
based on some simple expriments I have done.


This is the case on all platforms, but far more sensible on Windows: Windows attempts to be "clever" and corrects the font size you give depending on your screen resolution so that a 12 point font is supposed to be actually 12/72 inches *on screen* (obviously ignoring the fact that this is almost never what you want, since all other dimensions are in screen points by default...). Other platforms than Windows are supposed to do this too, but (fortunately) it seems to fail and the computed factor is very close to 1 (I got something like 1.04 on Linux, whatever the screen resolution was).

To avoid this, you can try to use the winfo_* methods to get the screen resolution (I thought there was a more straightforward way, but the only way I see is to do someWidget.winf o_screenwidth() / someWidget.winf o_screenmmwidth (), with the usual adjustement to get inches instead of millimeters). You can then use this adjustement on all the dimensions you compute so that it will be consistent with the font sizes you get.

The other solution is to turn the adjustement off. You can do this at tk level with the command "tk scaling 1". Unfortunately, this command does not seem to be directly available at Tkinter level, so you'll have to do:
someWidget.tk.c all('tk', 'scaling', 1)
After doing that, all your font sizes should be in screen points. But be aware that *all* your fonts will seem to shrink (the screen resolutions these days are usually closer to 92 dpi than to 72...). So you may have to do some adjustements on other parts of your application (the biggest problem I got was with menu items).

HTH
--
python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz 5(17;8(%,5.Z65\ \'*9--56l7+-'])"
Jul 19 '05 #7
On Thu, 28 Apr 2005 10:36:18 +0200, "Eric Brunel"
<er*********@de spammed.com> declaimed the following in comp.lang.pytho n:
This is the case on all platforms, but far more sensible on Windows: Windows attempts to be "clever" and corrects the font size you give depending on your screen resolution so that a 12 point font is supposed to be actually 12/72 inches *on screen* (obviously ignoring the fact that this is almost never
Pardon? Since when has Windows attempted to scale fonts for
screen display based on screen resolution?

The older Macs were fixed at 72 pixels per inch -- with the
result that the /only/ way to increase the resolution was to physically
change to a larger monitor. This is why they were so popular for DTP --
the on-screen view WAS the same size as the printed view.

Windows display properties defaults to an /assumed/ 96 pixels
per inch regardless of the screen resolution (right-click the desktop
background, properties, Settings/Advanced, General). This is why
changing to a low-resolution (like the recovery mode screen on W98) on a
large monitor results in such a pixilated, large-character, display.

I'm currently running a 20" flat-panel at 1600x1200. It also
appears to be about 12" vertical display region, making for
100pixels/inch. If I set it to 800x600, it would be running at 50pixels
per inch -- even though Windows is still assuming 96ppi for rendering. A
12pt typeface would be just under 1/8" on normal, but 1/4" on the low
resolution setting.

-- =============== =============== =============== =============== == <
wl*****@ix.netc om.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
=============== =============== =============== =============== == <
Home Page: <http://www.dm.net/~wulfraed/> <
Overflow Page: <http://wlfraed.home.ne tcom.com/> <

Jul 19 '05 #8
On Thu, 28 Apr 2005 16:14:02 GMT, Dennis Lee Bieber <wl*****@ix.net com.com> wrote:
On Thu, 28 Apr 2005 10:36:18 +0200, "Eric Brunel"
<er*********@de spammed.com> declaimed the following in comp.lang.pytho n:
This is the case on all platforms, but far more sensible on Windows: Windows attempts to be "clever" and corrects the font size you give depending on your screen resolution so that a 12 point font is supposed to be actually 12/72 inches *on screen* (obviously ignoring the fact that this is almost never


Pardon? Since when has Windows attempted to scale fonts for
screen display based on screen resolution?

The older Macs were fixed at 72 pixels per inch -- with the
result that the /only/ way to increase the resolution was to physically
change to a larger monitor. This is why they were so popular for DTP --
the on-screen view WAS the same size as the printed view.

Windows display properties defaults to an /assumed/ 96 pixels
per inch regardless of the screen resolution (right-click the desktop
background, properties, Settings/Advanced, General). This is why
changing to a low-resolution (like the recovery mode screen on W98) on a
large monitor results in such a pixilated, large-character, display.

I'm currently running a 20" flat-panel at 1600x1200. It also
appears to be about 12" vertical display region, making for
100pixels/inch. If I set it to 800x600, it would be running at 50pixels
per inch -- even though Windows is still assuming 96ppi for rendering. A
12pt typeface would be just under 1/8" on normal, but 1/4" on the low
resolution setting.


Sorry for that: my mistake. Anyway, the problem remains; the ouput for the "tk scaling" command on Windows and Linux is as follows:

[Windows]
% tk scaling
1.33202228777

[Linux]
% tk scaling
1.04285347703

(all of this tested with tcl/tk 8.3 - Windows is Win2k, Linux is an old Mandrake 8.0).

So this means that when you ask for a 12 point font, Windows will give you a 12 * 1.33202228777 = 16 screen pixels font and Linux a 12 * 1.04285347703 = 12 or 13 screen pixels font, depending on how the size is rounded. But the dimensions you set for all widgets are in screen pixels, unless explicitely given in another unit. So either you do a "tk scaling 1" at the beginning of all your apps, or you specify all widget diemnsions as '100p' instead of just 100 for example. If you don't do either, all your texts will look really bigger on Windows than on Linux.
--
python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz 5(17;8(%,5.Z65\ \'*9--56l7+-'])"
Jul 19 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
2791
by: Ron Adam | last post by:
I want to be able to easily create reusable shapes in Tkinter and be able to use them in mid level dialogs. So after some experimenting I've managed to get something to work. The following does pretty much what I need, but I think it can be improved on. So could anyone take a look and let me know what you think? Some of the things I want to add, but aren't exactly sure how at this time: Nested groups Use tags to be able to change sub...
1
2656
by: C D Wood | last post by:
To whom this may concern, Below is the source code, which demonstrates a problem I am having making a GUI for my python project work. 'table.txt' is a file that is read from the same folder. My code writes to a text file 'table.txt', and 'table.txt' is displayed in
1
2433
by: alivip | last post by:
I integrat program to be GUI using Tkinter I try browser direction as you can see # a look at the Tkinter Text widget # use ctrl+c to copy, ctrl+x to cut selected text, # ctrl+v to paste, and ctrl+/ to select all # count words in a text and show the first ten items
1
5659
kaarthikeyapreyan
by: kaarthikeyapreyan | last post by:
Beginners Game- Tic-Tac-Toe My first attempt after learning Tkinter from Tkinter import * import tkFont class myApp: """ Defining The Geometry of the GUI And the variables Used In the The methods
2
3520
by: skanemupp | last post by:
so my little calculator works perfectly now. just having some trouble with the layout. this whole tkinter-thing seems to be more tricky than it should be. how can i make the 4 column of buttons have the same distance and size between them as the other 3 columns? and how can i make the top entry end where the 2nd row entry ends(meaning the top entry will be longer)? why are the 4th row split from the others? hard to fix the problems...
1
1830
by: viv1tyagi | last post by:
Hi everyone ! ! ! I'm just a month old in the world of Python and trying to develop an application using Tkinter in which a new window pops out on a particular button press.The code for this new window is in "AddKlas.py" file. The problem is all the content of the new window is overwritten on the previous window. Below is the code of the two files
3
2978
by: joshdw4 | last post by:
I hate to do this, but I've thoroughly exhausted google search. Yes, it's that pesky root window and I have tried withdraw to no avail. I'm assuming this is because of the methods I'm using. I guess my question is two-fold. 1) How do I get rid of that window? 2) Any comments in general? I am just learning python (and coding with classes), so I'm sure there are things I should pound into my head before I learn bad habits. Here's the...
0
1522
by: Kevin McKinley | last post by:
Below i've put the code for a program that i wrote. I need help on lines 384-403. If you run this program you will notice on the first tab when have it produce an answer the $ is surrounded with {$}. How can i get rid of that? from Tkinter import * class MyApp: def __init__(self, parent): self.myparent = parent
0
1503
by: Guilherme Polo | last post by:
On Wed, Sep 3, 2008 at 8:57 PM, Kevin McKinley <kem1723@yahoo.comwrote: Come on.. "help on lines 384-403", that is not a good way to look for help. You are supposed to post some minimal code that demonstrates the problem. Anyway, this demonstrates what you are getting (independent of python version): import Tkinter
1
1692
by: Francesco Bochicchio | last post by:
Il Mon, 18 Aug 2008 12:15:10 +0100, dudeja.rajat ha scritto: Uhm, I don't think you should use the grid manager to obtain a window like that. The grid manager is for equally distributing widgets both horizontally and vertically. And I'm not sure that you can realize that window look with Tkinter. You could get close by horizontally packing each widget row in a frame and then vertically packing the frames in the window. But the look...
0
8432
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8344
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8857
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8546
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7367
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6186
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4180
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4347
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2762
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.